POST Variables to function

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
sleepydad
Forum Commoner
Posts: 75
Joined: Thu Feb 21, 2008 2:16 pm

POST Variables to function

Post 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
anand
Forum Commoner
Posts: 80
Joined: Fri May 22, 2009 11:07 am
Location: India
Contact:

Re: POST Variables to function

Post by anand »

Try this

Code: Select all

 
$name=$_REQUEST['name'];
$address=$_REQUEST['address'];
 
Hope it helps
sleepydad
Forum Commoner
Posts: 75
Joined: Thu Feb 21, 2008 2:16 pm

Re: POST Variables to function

Post 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?
User avatar
Darhazer
DevNet Resident
Posts: 1011
Joined: Thu May 14, 2009 3:00 pm
Location: HellCity, Bulgaria

Re: POST Variables to function

Post 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.
Mark Baker
Forum Regular
Posts: 710
Joined: Thu Oct 30, 2008 6:24 pm

Re: POST Variables to function

Post 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;
}
 
Post Reply