检查mysql查询是否找到结果PHP

时间:2013-05-13 17:51:12

标签: php

如何检查它是否真的在php

中的mysql查询中找到了结果

例如

$usersearch=mysql_query("Select * FROM users WHERE username=$Searchboxinput");
if($usersearch==successfull){
//What happens when successfull
}
else{
//what happens when unsuccessfull
}

所以,如果它找到一个匹配$ searchboxinput的用户,它会做一些事情并且反之亦然

4 个答案:

答案 0 :(得分:3)

使用mysql_num_rows()

if(mysql_num_rows($usersearch) > 0){
//What happens when successfull
}
else{
//what happens when unsuccessfull
}

仅供参考,you shouldn't use mysql_* functions in new code。它们不再被维护and are officially deprecated。请参阅red box?转而了解prepared statements,并使用PDOMySQLi - this article将帮助您确定哪个。如果您选择PDO here is a good tutorial

您也可以SQL injections开放。

答案 1 :(得分:1)

尝试,

//mysql_query returns resource when successful 
if(mysql_num_rows($usersearch) > 0 ) {...}
else {...}

Manual

注意:不推荐使用Mysql_ *扩展程序。请尝试使用PDO或Mysqli扩展程序。

答案 2 :(得分:0)

像这样检查

$count = mysql_num_rows($usersearch);


if($count)>0) {
}

答案 3 :(得分:0)

如果查询能够执行(无论是否存在匹配),

$usersearch将包含指向查询结果集的指针,或者如果查询由于某种原因实际失败,则它将保留一个值false

因此,您需要检查结果集以查看是否确实返回了任何记录。通常只需使用mysql_num_rows()即可完成此操作。这是一个例子:

$usersearch=mysql_query("Select * FROM users WHERE username=$Searchboxinput");
if(false === $usersearch){
    // there was a problem running the query
    echo mysql_error();
} else if (mysql_num_rows($usersearch) === 0) {
    // no results were found
} else {
    //  you have at least one record returned
}

我还建议您学习使用mysqliPDO,因为mysql_*函数已弃用。