Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating a php function to return mysql results

Tags:

php

mysql

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
like image 418
mrpatg Avatar asked Aug 18 '09 06:08

mrpatg


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;
 }
like image 139
KV Prajapati Avatar answered Sep 20 '22 13:09

KV Prajapati


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;
like image 32
Tom Haigh Avatar answered Sep 20 '22 13:09

Tom Haigh