Mysql查询总是返回0结果

时间:2012-12-10 17:11:50

标签: php mysql

我想要做的是检查表中是否存在值。如果它不存在,则应显示失败的消息

   $mysqli = new mysqli("localhost","root","", "myusers");
    print($string);
    if ($mysqli->connect_errno) {
        printf("Failed1");
        exit();
    }

    else
    {
    if ($result=$mysqli->query("SELECT 1 FROM `users` WHERE `k1`='$string' AND 'k2'='$string2'"))
    {

    if($result->num_rows == 0)
    {
    printf("Failed2");
    }

此查询始终返回Failed2,尽管表中存在值。问题是什么,表有三个值k0,k1和k2但我只使用k1和k2进行SELECT Query.Please帮助

编辑:

我已经更改了代码,请问您已经建议删除'但现在查询将无法执行并将导致Failed3

<?php  

$string1=$_POST['value1'];
$string2=$_POST['value2'];
$mysqli = new mysqli("localhost","root","", "myusers");
print($string);
if ($mysqli->connect_errno) {
    printf("Failed1");
    exit();
}

else
{
    if ($result=$mysqli->query("SELECT 1 FROM `users` WHERE k1='$string1' AND k2='$string2'"))
    {    
        if($result->num_rows == 0)
        {
            printf("Failed2");
        }
        else
        {
            //---------
        }
    }
    else
    {
         printf("Failed3");
    } 
}




?>

3 个答案:

答案 0 :(得分:3)

错字:

您使用了'而非反引号!

`k1`='$string' AND 'k2'='$string2'"
 ------------------^--^---------------- You have used single quotes!

将其替换为:

SELECT 1 FROM `users` WHERE `k1`='$string' AND `k2`='$string2'

答案 1 :(得分:0)

从表名和列名中删除反引号和引号,即

SELECT 1 FROM users WHERE  k1 ='$string' AND k2='$string2'

答案 2 :(得分:-1)

除非您有一个名为1的列。您不希望Select 1 from users

这将只返回一个结果,如果那就是你要找的东西

SELECT * FROM `users` WHERE `k1`='$string' AND `k2`='$string2' LIMIT 1