检查MySQL结果是否以PHP返回的最佳方法? [英] Best way to check if MySQL results returned in PHP?
问题描述
我正在寻找检查并查看查询是否返回任何结果的最佳方法.我觉得我经常写这部分代码,有时会出错,有时却没有.
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?
推荐答案
if (mysql_num_rows($result)==0) { PERFORM ACTION }
对于PHP 5和7及更高版本,请使用mysqli:
if (mysqli_num_rows($result)==0) { PERFORM ACTION }
这获得了我的投票.
OP假设查询未返回任何错误,因此这应该是其中一种方式
OP assuming query is not returning any error, so this should be one of the way
这篇关于检查MySQL结果是否以PHP返回的最佳方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!