[英]php return mysql_query
How is it possible to retrieve the mysql_query from a function? 如何从函数中检索mysql_query? For instance: 例如:
class A() {
...
function getAll($l=1) {
...
$result = mysql_query($query);
return $result
}
...
}
$a = new A();
$r = $a -> getAll(2);
while ($row = mysql_fetch_assoc($r)) {
// do something
}
This code above does not work when I return $result from the function. 当我从函数返回$ result时,上面的代码不起作用。 However, when I use the mysql_fetch_assoc function in getAll function, it works perfectly. 但是,当我在getAll函数中使用mysql_fetch_assoc函数时,它可以完美运行。 So basically, my question is how to return a mysql result set from a function? 所以基本上,我的问题是如何从函数返回mysql结果集?
** EDIT ** **编辑**
I actually get no errors. 我实际上没有任何错误。 The while statement used liked above will just not execute. 上面喜欢的while语句将不会执行。 But the query works perfectly when I execute it from within the getAll function. 但是,当我从getAll函数中执行查询时,查询效果很好。
Don't return the result resource from the query, but rather return the data extracted from that resource: 不要从查询中返回结果资源,而是返回从该资源中提取的数据:
$data = array();
while ( $row = mysql_fetch_assoc($result) ) {
$data[] = $row;
}
return $data;
Absolutely it works. 绝对可以。
Do a var_dump($r)
to make sure you're getting a resource. 执行var_dump($r)
以确保获得资源。 If not, double-check your SQL. 如果不是,请仔细检查您的SQL。 There may be an error in it. 可能有错误。
Also turn on other error reporting at the top of your script (as well as checking mysql_error
) for better clues as to what's wrong: 还要在脚本顶部打开其他错误报告(以及检查mysql_error
),以获得有关错误原因的更好线索:
ini_set('display_errors', true);
error_reporting(E_ALL);
You've edited much of your code so it's difficult to investigate further. 您已经编辑了许多代码,因此很难进行进一步调查。 Just make sure that your method is not closing the mysql connection. 只要确保您的方法没有关闭mysql连接即可。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.