Andrew R Posted February 3, 2009 Share Posted February 3, 2009 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 Quote Link to comment Share on other sites More sharing options...
GingerRobot Posted February 3, 2009 Share Posted February 3, 2009 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); ?> Quote Link to comment Share on other sites More sharing options...
Vebut Posted February 3, 2009 Share Posted February 3, 2009 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); ?> Quote Link to comment Share on other sites More sharing options...
Andrew R Posted February 3, 2009 Author Share Posted February 3, 2009 Thanks a million! Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.