mrpatg
mrpatg

Reputation: 10117

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

Upvotes: 7

Views: 31858

Answers (2)

KV Prajapati
KV Prajapati

Reputation: 94635

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

Upvotes: 11

Tom Haigh
Tom Haigh

Reputation: 57815

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;

Upvotes: 11

Related Questions