即使db为空,SELECT总是返回一些东西

时间:2013-08-18 07:00:44

标签: php mysql

我的问题是,结果总是大于0并且他一直在告诉数据库内部有什么东西,但事实上数据库是空的,可能是什么原因?我一定做错了。

提前致谢。

<?php
   header("Content-type: text/html; charset=utf8");

   $connection = mysql_connect("localhost","username","password"); //   Your Username and Password
   if(!$connection)
   {
       die("database connection failed:" . mysql_error());       
   }
   $db = mysql_select_db("database_name",$connection); //   The database name
   if(!db)
   {
       die("database connection failed:" . mysql_error());
   }
   mysql_query("SET NAMES 'utf8'",$connection);
?>

<?php

    $varGet1 = $_POST['deviceToken'];
    $varGet2 = $_POST['uniqueIdentifier'];

    $result = mysql_query("SELECT * FROM `push_notification_users` WHERE uniqueIdentifier = '".$varGet2."'");
    if ($result > 0)
    {
        echo 'UDID found on Database. Not added.'; 
    }
    else
    {
        $result = mysql_query("INSERT INTO `push_notification_users` (`deviceToken`,`uniqueIdentifier`) VALUES ('".$varGet1."','".$varGet2."')");

        if($result === FALSE)
        {
            die(mysql_error());
        }
        else
        {
            $message = "UDID didnt found on Database. Added successfully";
            echo $message;
        }
    }

    mysql_close($connection);
?>

2 个答案:

答案 0 :(得分:1)

这是正确的行为。对于select查询,mysql_query在出错时返回RESOURCE或false,并且您无法执行if ($result > 0)。因此,如果查询正确,则转换为int的$ result将始终大于0.您应该使用if (mysql_num_rows($result) > 0)

答案 1 :(得分:0)

试试这个:

$ result = mysql_num_rows(mysql_query(“SELECT * FROM push_notification_users WHERE uniqueIdentifier ='”。$ varGet2。“'”));     if($ result&gt; = 1)     {         echo'在数据库中找到的UDID。没有添加。';     }