php 创建一个php函数来返回mysql结果
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1292210/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Creating a php function to return mysql results
提问by mrpatg
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.
我试图创建一个函数,它将返回一个 mysql 查询,然后我可以循环并处理结果,但它似乎不起作用。我什至可能没有以正确的方式这样做。
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
回答by adatapost
Remove double quotes around the link variable $result.
删除链接变量周围的双引号$result。
function GetAccounts($username){
require("dbconn.php");
$result = mysql_query("SELECT * FROM `accounts` WHERE `username` = '$username' ") or trigger_error(mysql_error());
return $result;
}
回答by Tom Haigh
Putting $resultwithin double quotes means it will be cast to a string, and is then no longer of type 'resource'. Try instead:
放在$result双引号内意味着它将被转换为字符串,然后不再是“资源”类型。试试吧:
return $result;

