遇到问题,如果行等于0,则不调用else语句。如果我在网站上输入正确的详细信息,则会满足第一个条件并显示xml,但是如果输入了错误的详细信息,则不会显示错误xml。
echo "<users>";
$result = mysql_query("SELECT * FROM `numbers` WHERE `email` = '".$email."' AND `password` = '".$password."'") or die('Invalid query: ' . mysql_error());
if (!$result) die('Invalid query: ' . mysql_error());
while ($row = mysql_fetch_array($result, MYSQL_ASSOC))
{
if(mysql_num_rows($result) != 0)
{
echo "<usercallback>";
echo "<id>".$row['id']."</id>";
//echo "<number>".$row2['number']."</number>";
//echo "<gender>".$row2['gender']."</gender>";
//echo "<relationship>".$row2['relationship']."</relationship>";
echo "</usercallback>";
}
else
{
echo "<usercallback>";
echo "<id>error</id>";
echo "</usercallback>";
}
}
echo "</users>";
答案 0 :(得分:6)
实际上你必须将if mysql_num_rows检查放在while块
之外echo "<users>";
$result = mysql_query("SELECT * FROM `numbers` WHERE `email` = '".$email."' AND `password` = '".$password."'") or die('Invalid query: ' . mysql_error());
if(mysql_num_rows($result) != 0)
{
while ($row = mysql_fetch_array($result, MYSQL_ASSOC))
{
echo "<usercallback>";
echo "<id>".$row['id']."</id>";
//echo "<number>".$row2['number']."</number>";
//echo "<gender>".$row2['gender']."</gender>";
//echo "<relationship>".$row2['relationship']."</relationship>";
echo "</usercallback>";
}
}
else
{
echo "<usercallback>";
echo "<id>error</id>";
echo "</usercallback>";
}
echo "</users>";
答案 1 :(得分:0)
while ($row = mysql_fetch_array($result, MYSQL_ASSOC))
如果没有行,那么$row
将为false
,并且它永远不会进入上面的while循环。
所以你不能得到错误信息
答案 2 :(得分:0)
在执行循环时检查行,您应该检查while循环之前的行数。
答案 3 :(得分:0)
看起来你期待MySQL的零行响应导致undef $结果。这不是发生的事情。如果出现错误,mysql_query()
将返回null。您可以测试其返回值的“真实性”,以查看查询是否正确运行。如果查询导致0行响应,则正确运行。要测试的值是mysql_num_rows($result)
。
然而,它可以更简单。我通常这样写:
$res = mysql_query("SELECT 1");
if (!$res) {
//do whatever error reporting if the SQL was bad
//though you should probably deal with any condition that ends up
//here before you go into production!
}
if (mysql_num_rows($res) == 0) {
//put out my "no results found" message
}
while ($row = mysql_fetch_assoc($res)) {
//do my per-row business
}
当没有(或没有)结果返回时, mysql_fetch_assoc()
返回false。因此,如果它为空,则while循环将永远不会运行,因此它不需要位于else
内。