检查 MySQL 结果是否在 PHP 中返回的最佳方法?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4286586/
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
Best way to check if MySQL results returned in PHP?
提问by timroman
I'm looking for the best way to check and see if any results were returned in a query. I feel like I write this part of code a lot and sometimes I get errors, and sometimes I don't.
我正在寻找检查并查看查询中是否返回任何结果的最佳方法。我觉得这部分代码我写了很多,有时我会出错,有时我不会。
For example, I run this query to check if a username exists before inserting a new one into the database.
例如,我运行此查询以在将新用户名插入数据库之前检查用户名是否存在。
$result = mysql_query("SELECT * FROM ...");
Then I want to check and see if any results were returned. Here is one way I do it:
然后我想检查一下是否返回了任何结果。这是我这样做的一种方法:
if (!$result) { PERFORM ACTION }
If the first way doesn't work, then sometimes this will:
如果第一种方法不起作用,那么有时会:
if (mysql_num_rows($result)==0) { PERFORM ACTION }
Then I even saw that I could do it this way the other day:
然后我什至有一天看到我可以这样做:
list($total) = mysql_fetch_row($result);
if ($total==0) { PERFORM ACTION }
What is the best way to do this?
做这个的最好方式是什么?
回答by benhowdle89
if (mysql_num_rows($result)==0) { PERFORM ACTION }
For PHP 5 and 7 and above use mysqli:
对于 PHP 5 和 7 及以上版本,请使用 mysqli:
if (mysqli_num_rows($result)==0) { PERFORM ACTION }
This gets my vote.
这得到了我的投票。
OP assuming query is not returning any error, so this should be one of the way
OP假设查询没有返回任何错误,所以这应该是其中一种方式
回答by Shoe
One way to do it is to check what mysql_num_rows
returns. A minimal complete example would be the following:
一种方法是检查mysql_num_rows
返回的内容。一个最小的完整示例如下:
if ($result = mysql_query($sql) && mysql_num_rows($result) > 0) {
// there are results in $result
} else {
// no results
}
But it's recommended that you check the return value of mysql_query
and handle it properly in the case it's false
(which would be caused by an error); probably by also calling mysql_error
and logging the error somewhere.
但建议您检查 的返回值mysql_query
并在情况下正确处理它false
(这可能是由错误引起的);可能还通过mysql_error
在某处调用并记录错误。
回答by Shahnawaz Akhtar
Whenever we do queries to get some data, it is returned as an object. Then most of us convert it to array for looping through the rows easily. In php "empty()" function is used to check if an array is empty i.e. if it has no data in it. So we can check if returned array representation of query isn't empty by doing like this
每当我们进行查询以获取某些数据时,它都会作为对象返回。然后我们大多数人将其转换为数组,以便轻松遍历行。在 php 中,“empty()”函数用于检查数组是否为空,即其中是否没有数据。所以我们可以通过这样做来检查查询的返回数组表示是否为空
if(!empty($result)){
//DO STUFF
}
回答by G. Moore
What is more logical then testing the TYPE of the result variable before processing? It is either of type 'boolean' or 'resource'. When you use a boolean for parameter with mysqli_num_rows, a warning will be generated because the function expects a resource.
有什么比在处理之前测试结果变量的 TYPE 更合乎逻辑?它是“布尔值”或“资源”类型。当您对 mysqli_num_rows 参数使用布尔值时,将生成警告,因为该函数需要资源。
$result = mysqli_query($dbs, $sql);
if(gettype($result)=='boolean'){ // test for boolean
if($result){ // returned TRUE, e.g. in case of a DELETE sql
echo "SQL succeeded";
} else { // returned FALSE
echo "Error: " . mysqli_error($dbs);
}
} else { // must be a resource
if(mysqli_num_rows($result)){
// process the data
}
mysqli_free_result($result);
}
回答by martynthewolf
Of all the options above I would use
在上述所有选项中,我会使用
if (mysql_num_rows($result)==0) { PERFORM ACTION }
if (mysql_num_rows($result)==0) { PERFORM ACTION }
checking against the result like below
检查结果如下
if (!$result) { PERFORM ACTION }
This will be true if a mysql_error occurs so effectively if an error occurred you could then enter a duplicate user-name...
如果 mysql_error 如此有效地发生,如果发生错误,您可以输入重复的用户名,那么这将是正确的...
回答by Toki
$connect = new mysqli('localhost', 'user', 'password', 'db');
$result = $connect->query("select * from ...");
$count=$result->num_rows;
if(empty($count)){
echo"Query returned nothing";
}
else{
echo"query returned results";
}
回答by cristian
Use the one with mysql_fetch_row
because "For SELECT, SHOW, DESCRIBE, EXPLAIN and other statements returning resultset, mysql_query() returns a resource on success, or FALSE on error.
使用一个 withmysql_fetch_row
因为“对于 SELECT、SHOW、DESCRIBE、EXPLAIN 和其他返回结果集的语句,mysql_query() 在成功时返回资源,或者在错误时返回 FALSE。
For other type of SQL statements, INSERT, UPDATE, DELETE, DROP, etc, mysql_query() returns TRUE on success or FALSE on error. "
对于其他类型的 SQL 语句,INSERT、UPDATE、DELETE、DROP 等,mysql_query() 在成功时返回 TRUE,在错误时返回 FALSE。”
回答by Amirouche Douda
Usually I use the ===
(triple equals) and __LINE__
, __CLASS__
to locate the error in my code:
通常我使用===
(三重等于)和__LINE__
,__CLASS__
来定位我的代码中的错误:
$query=mysql_query('SELECT champ FROM table')
or die("SQL Error line ".__LINE__ ." class ".__CLASS__." : ".mysql_error());
mysql_close();
if(mysql_num_rows($query)===0)
{
PERFORM ACTION;
}
else
{
while($r=mysql_fetch_row($query))
{
PERFORM ACTION;
}
}
回答by D. Mariano
If you would still like to perform the action if the $result
is invalid:
如果您仍然希望在$result
无效的情况下执行该操作:
if(!mysql_num_rows($result))
// Do stuff
This will account for a 0
and the false
that is returned by mysql_num_rows()
on failure.
这将解释失败时返回的a0
和。false
mysql_num_rows()
回答by xavier bs
mysqli_fetch_array()
returns NULL
if there is no row.
mysqli_fetch_array()
NULL
如果没有行则返回。
In procedural style:
在程序风格中:
if ( ! $row = mysqli_fetch_array( $result ) ) {
... no result ...
}
else {
... get the first result in $row ...
}
In Object oriented style:
在面向对象的风格中:
if ( ! $row = $result->fetch_array() ) {
...
}
else {
... get the first result in $row ...
}