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
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);
?>

 

Link to comment
Share on other sites

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);
?>

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.