简体   繁体   中英

Creating a php function to return mysql results

Im trying to create a function, that will return a mysql query, which i can then loop through and handle the results, but it doesnt seem to be working. I might not even be doing this the right way.

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;
}

The error i recieve is

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

I tried loading all of the above into the function, but could only get it to return a single result each time. Since ill need to handle each result, i "think" the above way is how i want to do it, but let me know if there is a better way, or what im doing wrong.

When i echo the function with the username, i get the following;

Resource id #5

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;
 }

Putting $result within double quotes means it will be cast to a string, and is then no longer of type 'resource'. Try instead:

return $result;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM