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 Link to comment https://forums.phpfreaks.com/topic/143603-sql-results-in-php-function/ 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); ?> Link to comment https://forums.phpfreaks.com/topic/143603-sql-results-in-php-function/#findComment-753455 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); ?> Link to comment https://forums.phpfreaks.com/topic/143603-sql-results-in-php-function/#findComment-753457 Share on other sites More sharing options...
Andrew R Posted February 3, 2009 Author Share Posted February 3, 2009 Thanks a million! Link to comment https://forums.phpfreaks.com/topic/143603-sql-results-in-php-function/#findComment-753464 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.