Creating a php function to return mysql results

I am trying to create a function that will return a mysql query, which then I can execute and process the results, but it does not seem to work. I may not even do it right.

function GetAccounts($username){ require("dbconn.php"); $result = mysql_query("SELECT * FROM `accounts` WHERE `username` = '$username' ") or trigger_error(mysql_error()); return "$result"; } $result = GetAccounts($username); while($row = mysql_fetch_array($result)){ foreach($row AS $key => $value) { $row[$key] = stripslashes($value); } $theusername = $row['theusername']; $thepassword = $row['thepassword']; echo $theusername; } 

I get an error

 Warning: mysql_fetch_array(): supplied argument is not a valid MySQL result resource 

I tried loading all of the above into a function, but could only make it return one result each time. Since I don’t need to process each result, I think that this is the way I want to do it, but let me know if there is a better way or what I am doing wrong.

When I repeat the function with the username, I get the following:

 Resource id #5 
+6
php mysql
source share
2 answers

Remove double quotes around the link variable $result .

 function GetAccounts($username){ require("dbconn.php"); $result = mysql_query("SELECT * FROM `accounts` WHERE `username` = '$username' ") or trigger_error(mysql_error()); return $result; } 
+9
source share

Entering $result in double quotes means that it will be passed to a string, and then it will no longer be a "resource" type. Try instead:

 return $result; 
+9
source share

All Articles