SQL where clause giving a null result

时间:2015-07-28 16:18:45

标签: php mysql if-statement where-clause

I have the following simple php code that gives me a result that I want to display.

$linkz= mysql_connect($host,$username,$password) or die(mysql_error());
mysql_select_db($db, $linkz);


$sq_name= $_POST['unameTF'];
$sq_pass= $_POST['passTF'];
$sq_search= $_POST['searchTF'];

if($sq_search=""||$sq_search=null)
{
echo "type something";
}else
{
$sql2= "SELECT * FROM sql_insert WHERE sq_name='$sq_search' ";
$res= mysql_query($sql2, $linkz) or die(mysql_error());
}

    while($row=mysql_fetch_assoc($res))
    }
    echo "$row[sq_name]"."<br/>";
    }

This gives me a null result always(ie it doesn't give an error or dispay anything). It works fine when the if-else statement is removed meaning it just

$sql2= "SELECT * FROM sql_insert WHERE sq_name='$sq_search' ";
$res= mysql_query($sql2, $linkz) or die(mysql_error());

and no checking to see if its null.

and also if I replace

$sql2= "SELECT * FROM sql_insert WHERE sq_name='$sq_search' ";

with

$sql2= "SELECT * FROM sql_insert WHERE sq_name='".$_POST['searchTF']."' ";

(even without removing the if-else statement)

Can someone explain whats going on?

2 个答案:

答案 0 :(得分:1)

The reason why it works without the if() statement is because you used assignment operators, rather than comparison operators causing the flow of your if statement to work like this:

if we can set $sq_search = "" ... we can!
    check that it's not a null-terminated value... that's good too!
if we can set $sq_search = null ... we can!
    check that it's not a null-terminated value... it is, this answer is false
do that else statement,
    compile the string, output will be: "SELECT * FROM sql_insert WHERE sq_name=''"

replace your if statement with this:

if($sq_search===""||is_null($sq_search)){
    echo "type something";
} else {
    $sql2= "SELECT * FROM sql_insert WHERE sq_name='$sq_search' ";
    $res= mysql_query($sql2, $linkz) or die(mysql_error());
}

答案 1 :(得分:0)

if ((!isset($_POST['searchTF'])) || (empty($_POST['searchTF']))
{
echo "type something";
} else