检查 mysql_query 是否返回任何结果的最佳方法? [英] Best way to check if mysql_query returned any results?

查看:33
本文介绍了检查 mysql_query 是否返回任何结果的最佳方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找检查和查看查询中是否返回任何结果的最佳方法.我感觉这部分代码我写了很多,有时会出错,有时不会.

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 }

最好的方法是什么?

推荐答案

if (mysql_num_rows($result)==0) { PERFORM ACTION }

对于 PHP 5 和 7 及以上版本,请使用 mysqli:

if (mysqli_num_rows($result)==0) { PERFORM ACTION }

这篇关于检查 mysql_query 是否返回任何结果的最佳方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆