简体   繁体   中英

Mysql query always returning 0 results

What im trying to do is checking if a value exists in the table.If it does not exist a Failed message should be displayed

   $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");
    }

This query is always returning Failed2 inspite of the fact that the values are existing in the table.what is the problem,The table has three values k0,k1 and k2 but i use only k1 and k2 for SELECT Query.Please help

EDIT:

I have changed the code ask you have suggested by removing ' but now the query will not execute and will lead to 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");
    } 
}




?>

Typo here:

You used ' s instead of backticks!

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

Replace it with:

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

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

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

Unless you have a column called 1. You dont want to Select 1 from users

This will return one result only, if thats what you were looking for

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM