Jump to content

[SOLVED] Global Variables In PHP Functions - Please Help


jjacquay712

Recommended Posts

I have a function that assigns the data from an sql query to a variable in php, but the variable only seems to be working inside the function. is there anyway to make the variable global? Here is my code:

 

<?php
//Connect
$con = mysql_connect("localhost", "johnj_admin", "******") or die(mysql_error());
mysql_select_db("johnj_program", $con) or die(mysql_error());
//End Connect


function echosqlquery($sqlquery){
    $query  = $sqlquery;
$result = mysql_query($query);
while($row = mysql_fetch_array($result, MYSQL_ASSOC))
{
    	$row['username'] = $a;
} 
}

echosqlquery("SELECT * FROM users WHERE username='jjacquay712'");
echo $a;



?>

 

thanks For the help

assignments go left to right, first of all.  that means to give $a the value of $row['username'], you need to use:

 

$a = $row['username'];

 

second, the while() loop is pointless, since you'll constantly overwrite $a.  might as well just use mysql_fetch_assoc() alone:

 

$result = mysql_query($query);
$row = mysql_fetch_assoc($result);

 

third, variables generated and defined within the function stay in that function's namespace.  this is called "scope," and is worth a bit of reading up on in the manual.  the short answer is, to fetch that value from outside of the function, you need to return it:

 

function echosqlquery($sqlquery){
  $result = mysql_query($sqlquery);
  $row = mysql_fetch_assoc($result);
  return $row['username'];
}

$a = echosqlquery("SELECT * FROM users WHERE username='jjacquay712'");
echo $a;

 

for the record, your function isn't saving you any time since it will only return $row['username'].  you might as well do this:

 

$resource = mysql_query("SELECT * FROM users WHERE username='jjacquay712'");
$a = mysql_result($resource, 0, 'username');

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.