Variable invisible outside a function - php

I have written a query to get customer information from my database but say I want to use it on another page. I don't want to have to copy and paste to the other page to use it.
I have looked at a function but I don't know how to get the variables out of the function.
This is my current function:
function getCustomer($customerid) {
$getcustomer = mysql_query("SELECT * FROM hire_customers WHERE id='".$customerid."'");
$fetch = mysql_fetch_assoc($getcustomer);
$cust_firstname = $fetch['firstname'];
$cust_lastname = $fetch['lastname'];
$cust_address = $fetch['address'];
$cust_town = $fetch['town'];
$cust_postcode = $fetch['postcode'];
$cust_cont1 = $fetch['contact1'];
$cust_number1 = $fetch['contactnumber1'];
$cust_cont2 = $fetch['contact2'];
$cust_number = $fetch['contactnumber2'];
$cust_email = $fetch['email'];
$cust_idform1 = $fetch['idform1'];
$cust_idnfo1 = $fetch['idinfo1'];
$cust_idform2 = $fetch['idform2'];
$cust_idinfo2 = $fetch['idinfo2'];
$cust_enterdby = $fetch['enteredby'];
}
This is my customer page
getCustomer($customerid);
echo $cust_firstname;
but nothing is echoed out.
Do I need to be looking at a class or object to do this? Have I gone wrong with my function.
What I would like to do is have a PHP file with all my customer functions (update, select, etc) in one place.

I think you should just return $fetch and then access it as a variable outside of the function.
function getCustomer($customerid) {
$customerid = mysql_real_escape_string($customerid);
$getcustomer = mysql_query("SELECT * FROM hire_customers WHERE id='".$customerid."'");
$fetch = mysql_fetch_assoc($getcustomer);
return $fetch;
}
$data=getCustomer($customerid);
echo data['firstname'];

This should get you started:
function getCustomer($customerid) {
$getcustomer = mysql_query("SELECT * FROM hire_.. etc");
$customer_data = mysql_fetch_assoc($getcustomer);
return $customer_data; // return here
}
$customer = getCustomer($customerid);
$cust_firstname = $customer['firstname'];

you need to return a value from your function return $variable;

In your code, variable $cust_firstname; is visible only inside that function.
Please read this: PHP variable scope
It works like this to reduce memory usage on web server - when function ends - variable is destroyed and memory freed.
Basically - you have to return that value somehow. Dave Chen wrote nice answer above/below, you can use his code.
BTW you can use extract(); function and reduce your code size and save a lot of time.
It works like this:
$fetch = mysql_fetch_assoc($getcustomer);
extract($fetch, EXTR_PREFIX_ALL, "cust_"); // creates variables from associative array
echo $cust_firstname; // magic! :)

Related

issue with getting result object of mysql query into a function

I have a function to process info from a database. This is called multiple times in a page. And I don't want to query the database every time. So I put the query outside. If I do that, the function doesn't work. I know this can be done because, there was a similar question somewhere in SO. But that addressed a different situation. I don't know what is wrong here. Any help will be greatly appreciated.
If I put all this code into a separate test file including the conn file and query, it works. But in my main page, where I have the functions.php included first, then conn.php and then the query and then the display code called by js fadein event, the $result refuses to work inside the function
EDIT : This code has been cleaned up as per comments received (globals replaced with variables passed to the function and variable names rationalised)
function total($item,$result,$val){
global $totRate;
while($getRates=$result->fetch_assoc()){
$gotItem= strtolower(preg_replace('/[^(\x20-\x7F)]*/',"",$getRates['item']));
$gotItem=str_replace(array("_"," ","/"),"",$gotItem);
if($item==$gotItem){
$rate= $getRates['rate'];
$totRate=$val*$rate;
return $totRate;
}
}
}
The Result Call PHP file
$query = "SELECT * FROM rates ORDER BY item";
$result = $orderdb->query($query)
if (isset($_POST[$itemname]) && !empty($_POST[$itemname])) {
$val=$_POST[$itemname];
total($itemname);
echo $totprate;
} else {
echo "0";
}
I am writing this with the assumption that your SQL is working but are having problems displaying what you want - this may help. The code below saves your $result variable from your query and then passes it into the total function as a second parameter. Previously you were returning $totprate from total but you were not saving it anywhere - it is now saved to the $totprate variable.
Note: I cannot see $orderdb anywhere in your code, I'm assuming you have that in your file and that it is working.
function total($item, $result){
global $val;
global $pid;
global $pitem;
global $prate;
global $totprate;
global $gotitem;
global $getratess;
// global variable for $result removed so it doesn't overwrite variable passed to function
while($getratess=$result->fetch_assoc()){
$gotitem= strtolower(preg_replace('/[^(\x20-\x7F)]*/',"",$getratess['item']));
$gotitem=str_replace(array("_"," ","/"),"",$gotitem);
if ($item==$gotitem) {
$pid=$getratess['id'];
$pitem= $getratess['item'];
$prate= $getratess['rate'];
$totprate=$val*$prate;
return $totprate;
}
}
}
$query = "SELECT * FROM rates ORDER BY item";
$result = $orderdb->query($query);
if (isset($_POST[$itemname]) && !empty($_POST[$itemname])) {
$val=$_POST[$itemname];
$totprate = total($val, $result); // pass itemname as first parameter and result array as second parameter and save it to the $totprate variable
echo $totprate;
} else {
echo "0";
}
Let me know if this helps.

I want to take the variable that contains a mysql query from one php file, and write the loop that will print the query contents in another php file

I am a beginner trying to make a webpage where a schedule of reservations is being retrieved from the database. In a php file I have a class that has a function that creates a query using a SELECT statement, here is the function
public function getDTodayScheduleDB(){
$session=Modulator::getSession();
$session->start();
$currentdrID=$_SESSION['userID'];
$todayDate = date("Y/m/d");
$getTSchedule = "SELECT time, user.name FROM reservation FULL JOIN user ON childID = user.ID AND doctorID = '$currentdrID' AND date = '$todayDate'";
$result = Modulator::getDb()->query($getTSchedule);
return $result;
}
I am not sure if this is the right way to do it or not but I read this when I tried googling it. the $result variable is returned in a php file and used like this
<?php
include realpath($_SERVER['DOCUMENT_ROOT'] . '/Classes/Models/DoctorModel.php');
$scheduleResult = DoctorModel::getDTodayScheduleDB();
while($row = mysqli_fetch_assoc($scheduleResult)){
$appTime = $row['time'];
$childName = $row['name'];
echo"<tr>";
echo"<td>".$appTime."</td>";
echo"<td>".$childName."</td>";
echo"</tr>";
}
?>
However I do not know why it is not working although I tested the query elsewhere and it works so he problem is with the variable passing from the function to the other page I guess.
Using the :: operator, you are calling a non static (i.e instance method) function as if it was a static function. Assuming that your getDTodayScheduleDB is inside a DoctorModel class, you have to define it this way:
public static function getDTodayScheduleDB(){
//your code here
}

Web browser is returning nothing - function error?

When I access this from a web browser it returns nothing other than echo'd text, I know this is similar to another question I posted but I can't make sense of it?
<?php
include('config.php');
include('database.php');
class conversion{
public $amnt;
public $cc_from;
public $cc_to;
public function __construct (){
$this->amnt = htmlspecialchars($_GET["amnt"]);
$this->cc_from = htmlspecialchars($_GET["from"]);
$this->cc_to = htmlspecialchars($_GET["to"]);
}
function convert($this->amnt,$this->cc_from,$this-cc_to,$decimals=2){
$db_rate_from = mysql_query("SELECT * FROM _currency WHERE country_code='$this- >cc_from'") or die(mysql_error());;
$query_row_from = mysql_fetch_array($db_rate_from);
$rate_from = ($query_row_from['rate']);
echo $rate_from;
echo "</br>rate to</br>";
$db_rate_to = mysql_query("SELECT * FROM _currency WHERE country_code='$this->cc_to'") or die(mysql_error());;
$query_row_to = mysql_fetch_array($db_rate_to);
$rate_to = ($query_row_to['rate']);
echo $rate_to;
echo "</br>conversion</>";
$conversion = (number_format(($amnt/$rate_from)*$rate_to,$decimals));
echo $conversion;
} }
$var = new conversion();
$var->convert($amnt,$cc_from,$cc_to);
?>
Given this:
$db_rate_from = mysql_query("SELECT * FROM $db_tbprefix WHERE country_code='$this->cc_from'");
where is $db_tbprefix defined? Nowhere, causing your query to be SELECT * FROM WHERE .... If you had proper SQL error handling code, this would've been clear to you. At absolute bare minimum, you should have something like:
$result = mysql_query("...") or die(mysql_error());
which would abort the script on a query failure and tell you exactly why the query failed.
As well, htmlspecialchars is NOT intended for database operations. It does absolutely nothing to prevent SQL injection. For that, you have to use mysql_real_escape_string().
One thing I notice is that you call your method without parameters.
$var->convert();
Yet it is declared to take three mandatory parameters.
function convert($amnt,$cc_from,$cc_to,$decimals=2)
And btw, don't use $query_row_to[rate]. Use either $query_row_to['rate'] or $query_row_to[$rate].
Edit:
How about something like this? Use global $db_tbprefix and skip object orientation.
<?php
include('config.php');
include('database.php');
function convert($amnt,$cc_from,$cc_to,$decimals=2) {
global $db_tbprefix;
$db_rate_from = mysql_query("SELECT rate FROM $db_tbprefix WHERE country_code='$cc_from'") or die mysql_error();
$query_row_from = mysql_fetch_assoc($db_rate_from);
$rate_from = $query_row_from['rate'];
$db_rate_to = mysql_query("SELECT rate FROM $db_tbprefix WHERE country_code='$cc_to'") or die mysql_error();
$query_row_to = mysql_fetch_assoc($db_rate_to);
$rate_to = $query_row_to['rate'];
return number_format(($amnt/$rate_from)*$rate_to,$decimals);
}
echo convert(floatval($_GET["amnt"]), mysql_real_escape_string($_GET["from"]), mysql_real_escape_string($_GET["to"]));
?>
Edit 2: only select what you need, in this case rate. And use mysql_fetch_assoc rather than than mysql_fetch_array which will double your memory consumption and slow down your code.
haven' tested it ... but the possibility i can find is you are passing parameters in function convert while defining it so you need to pass the same param while calling it... OR if the variables are the reference from the predefined one then use them like this
function convert($this->amnt,$this->cc_from,$this->cc_to,$decimals=2){
}

PHP convert session variable from array into int

I am storing session information in an array called 'Auth'. That array contains 2 session information: id and password. My problem is when I am using the id info for quering, it is not working. I am pretty sure it is due to the fact that the id info in my table is an int, and the one from the session array isn't. So my question is to know how to convert that session id variable into an int. Here below the function in which I am using $_SESSION(['Auth']['id']). Thank you in advance for your replies. Cheers. Marc
The PHP code where I am using the session info:
<?php
session_start();
header('Content-Type: text/html; charset=utf-8');
require("connect.inc.php");
function isLogged(){
if(isset($_SESSION['Auth']) && isset($_SESSION['Auth']['id']) && isset($_SESSION['Auth']['pass'])){
extract($_SESSION['Auth']);
$result = mysql_query("SELECT * FROM usr_users WHERE usr_id = '$id' AND usr_pass = '$pass'");
if(mysql_num_rows($result)==1){
return true;
}
else{
return false;
}
}
}
?>
Here the PHP code where I set the session info:
<?php
session_start();
header('Content-Type: text/html; charset=utf-8');
require("connect.inc.php");
$identifiant = mysql_real_escape_string($_POST['identifiant']);
$pass = sha1($_POST['pass']);
$result = mysql_query("SELECT * FROM users WHERE usr_pseudo = '$identifiant' AND usr_pass = '$pass'");
if(mysql_num_rows($result)==1){
$data=mysql_fetch_assoc($result);
$_SESSION['Auth']=array(
'id'=>$data['usr_id'],
'pass'=>$pass
);
}
echo mysql_num_rows($result);
?>
extract() is a horribly ugly function, and you should wipe its existence out of your mind.
There's no need for it, since it's purely a holdover from PHP's early "lazy" days, when it tried to do everything for you, causing in part the miserable security reputation PHP has.
You can directly embed session variables wherever you want, even when it's an arbitrarily "deep" array reference like your session is:
$sql = "SELECT ... WHERE id={$_SESSION['Auth']['id']} ...";
or even
$id = $_SESSION['Auth']['id']'
$sql = "SELECT ... WHERE id=$id";
will both work the same way, and not litter your variable namespace with useless junk.
You can cast any variable into any type by using the cast methods.
$usr_id = (int)$data['usr_id']
This would return a type of integer. If the id includes anything else but integers, 0 is returned.
http://php.net/manual/en/language.types.type-juggling.php
You should not query DB each time you'd like to check if the user is logged in. And you don't need to store password in the seesion.
You have to query db only once when you login user (your second part of the code).
And it would be better if you create a simple wrapper for your auth logic. Something like this simple class with static functions:
<?php
class Auth
{
public static function login($identifiant, $password)
{
// query db then
// $_SESSION['Auth']['id'] = value from db
return self::id();
}
public static function isLogged()
{
return (bool)self::id()
}
public static function id()
{
return (isset($_SESSION['Auth']['id'])) ? $_SESSION['Auth']['id'] : false)
}
public static function logout()
{
$_SESSION['Auth'] = array();
}
}
// usage
Auth::login($_POST['identifiant'], $_POST['password']);
if (Auth::isLogged()) {
$sql = "select * from posts where user = " . Auth::id() . "";
}
Auth::logout();
If you are "pretty sure it is due to the fact that the id info in (your) table is an int, and the one from the session array isn't".
Then here's a simple way to convert your session id from array into a variable (cast it).
$id = (int)$_SESSION['id'];
Hope it helps.
you should not enclose integers in single quotes in the SQL
try this
$result = mysql_query("SELECT * FROM usr_users WHERE usr_id = $id AND usr_pass = '$pass'");

PHP: call a string from another page function?

Can you do that? I just tried but it doesnt seem to work.
I have dbc.php included at top of my page, and in dbc.php at the bottom i created this function:
function getUserInfo($id) {
$thaString = mysql_query("SELECT * FROM users WHERE id = '$id'");
$thaString2 = mysql_query("SELECT * FROM users_profile WHERE uID = '$id'");
$showUR = mysql_fetch_array($thaString);
$showURP = mysql_fetch_array($thaString2);
}
So it would be easier for me to call them instead of running the queries all the time when i need them in other pages..
But when i try to do:
getUserInfo($showInfo["bID"]);
echo $showUR["full_name"];
I dont get any result, is there a smarter way to do this, if so how?
It's an issue of scope: $showUR is set inside getUserInfo(), so it's not available to the echo outside the function. There are lots of potential modifications you could make, but you may want to assign your values into an array and then return that array:
function getUserInfo($id) {
$user = array();
$thaString = mysql_query("SELECT * FROM users WHERE id = '$id'");
$thaString2 = mysql_query("SELECT * FROM users_profile WHERE uID = '$id'");
$user['showUR'] = mysql_fetch_array($thaString);
$user['showURP'] = mysql_fetch_array($thaString2);
return $user;
}
$user = getUserInfo($showInfo["bID"]);
echo $user['showUR']["full_name"];
Your functions have to return something for the values to be used, or $showUR and $showURP will just get lost once the function exits (ie: the scope will change). Something like:
function someFunc($arg) {
return "Hello, I am {$arg}";
}
$showUR = someFunc('name');
echo $showUR;
And please don't call stuff $thaString. First because it's a misnomer (mysql_query() doesn't return a string, it returns a resource or a boolean), Second because "tha" is so lame.
Let your function return the variable.
And then use $showUR = getUserInfo(...)
If you declare them outside the function, and then as globals inside the function you should be able to use them as you are now.

Categories