Page 1 of 1

POST Variables to function

Posted: Sat May 23, 2009 10:41 am
by sleepydad
I'm calling in variables using

Code: Select all

 
$name=$_POST['name'];
$address=$_POST['address'];
 
I want to use these throughout my script including in a function:

Code: Select all

 
function helloworld() {
$db=new mysqli(' ', ' ', ' , "$name");
$result=$db->query($query);
/*
stuff
here 
and
here
*/
$db=new mysqli(' ', ' ', ' , "$address");
$result=$db->query($query);
}
 
The variable is not passing to the function. I know this is a bonehead question, and I've googled a solution ad nauseam to no avail. I'm a pseudo-newbie to php, so be kind. I've tried declaring as global both inside and outside of the function ($name=$_POST['name']; global $name;). I've tried passing them as parameters to the function (ie function helloworld($name, $address)). Nothing's working. I know the variables are passing to the script because they work fine outside of the function.

Thanks in advance -
sleepydad

Re: POST Variables to function

Posted: Sat May 23, 2009 12:32 pm
by anand
Try this

Code: Select all

 
$name=$_REQUEST['name'];
$address=$_REQUEST['address'];
 
Hope it helps

Re: POST Variables to function

Posted: Sat May 23, 2009 1:11 pm
by sleepydad
Thanks for the reply anand. Unfortunately that didn't do it. I replaced

Code: Select all

 
$name=$_POST['name'];
 
with

Code: Select all

 
$name=$_REQUEST['name'];
 
Didn't do it.

Anyone else?

Re: POST Variables to function

Posted: Mon May 25, 2009 2:48 pm
by Darhazer
Read about variable scopes :-)

You are defining the variables in the global scope. To use them inside the function, you have to use the global keyword.

Re: POST Variables to function

Posted: Mon May 25, 2009 3:39 pm
by Mark Baker
Darhazer wrote:Read about variable scopes :-)

You are defining the variables in the global scope. To use them inside the function, you have to use the global keyword.
Or pass the variables as parameters to the function

Code: Select all

 
$name=$_POST['name'];
$address=$_POST['address'];
 
function helloworld($name,$address) {
   echo $name.'<br />'.$address;
}