Jump to content

SQL Results in php function


Andrew R

Recommended Posts

Hi there.  I have the following script.  I was wondering why the SQL results won’t display inside the function?  How do I pass sql results inside the function?

 

<?

$name_q = mysql_query("SELECT * FROM users where name = 'Andrew'") or die(mysql_error);
$name = mysql_fetch_array($name_q);

function test() {

echo $user['name']; 

}

test();


?>

 

Many thanks

Link to comment
https://forums.phpfreaks.com/topic/143603-sql-results-in-php-function/
Share on other sites

I'm first going to assume that this line:

 

echo $user['name']; 

 

Was supposed to be:

 

echo $name['name']; 

 

Since $name is the row.

 

In any case, this wont work, owing to variable scope - if you google that, you'll find plenty of material. In short, the variable $name is not available inside the function unless it's global (bad) or you pass it as a parameter, like so:

 

<?php
$name_q = mysql_query("SELECT * FROM users where name = 'Andrew'") or die(mysql_error);
$name = mysql_fetch_array($name_q);

function test($row) {

echo $row['name'];

}

test($name);
?>

 

You either need to define the variable as global within the function:

<?php
$name = mysql_fetch...;

function test ()
{
    global $name;
    echo $name['name'];
}
?>

 

Or you (as recommended) you could pass the result to the function by:

<?php
function test ($result)
{
    echo $result['name'];
}

$name = mysql_fetch...;
echo test($name);
?>

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.