if语句中的mysql_num_rows

时间:2012-03-25 07:18:19

标签: php mysql-num-rows

我面临的问题是,mysql_num_rows在代码中给出了输出1,但是当我在if语句中匹配wil 0时,它返回true并执行代码。 所以$ license返回........而不是它的实际值。

我尝试使用这些来调试问题。

  • 尝试使用print_r查看是否存在数据。 - 是的
  • 尝试在第一部分回显$ license - 返回正确的值。
  • 尝试检查mysql_num_rows的值 - 返回1.
  • 在if语句中将其与0匹配 - 如果该值为1,则返回true。

对此有何帮助?

$check = mysql_query("SELECT * FROM licenses WHERE email='$email'") or die(mysql_error
                                                                           ());
if (mysql_num_rows($check) > 0)
{
    while ($data = mysql_fetch_array($check))
    {
        print_r($data); // for test
        $name = $data['name'];
        $license = $data['pid'];
        echo $license; // test print 1
        $comments = $data['comments'];
    }

    if ($license == "Sgsmorgan")
        $license = "EWP Discounted Basic (Simpleleveraging)";
}

$count = mysql_num_rows($check); // for test
echo $count; // returns 1.
if (mysql_num_rows($check) == 0)
    $name = "";
$license = "...........";
echo $license;// test print 2
$comments = "Email doesnt exist in the database";

3 个答案:

答案 0 :(得分:3)

当然你的意思是:

if (mysql_num_rows($check)==0)
{
    $name = "";
    $license = "...........";
    echo $license; //Test print 2
    $comments = "Email doesnt exist in the database";
}

而不是

if (mysql_num_rows($check)==0)
$name = "";
$license = "...........";
echo $license; //Test print 2
$comments = "Email doesnt exist in the database";

不使用花括号表示只包含if语句下面的第一行。因此,$license始终设置为...........

始终使用大括号。

答案 1 :(得分:1)

我认为问题是,在那时,没有剩下的行,因为你的while循环已经获取了所有行。

如果我没记错的话,这段代码:

while ($ignored = mysql_fetch_array($check)) {
    echo "Got a row! Rows left: " . mysql_num_rows($check);
}

应输出如下内容:

Got a row! Rows left: 3
Got a row! Rows left: 2
Got a row! Rows left: 1
Got a row! Rows left: 0

答案 2 :(得分:1)

跟进David的根本原因,这是一个非常简单的修复:

$check = mysql_query("SELECT * FROM licenses WHERE email='$email'") 
         or die(mysql_error());

if (mysql_num_rows($check) > 0) {
    while ($data = mysql_fetch_array($check)) {
        $name    = $data['name'];
        $license = $data['pid'];
        $comments = $data['comments'];
    }

    $license = ($license == "Blahblah") ? "This is a second level license" : $license;

} else {
    $name = "";
    $license = "...........";
    $comments = "Email doesnt exist in the database";
}