Php sql查询应为null但不是[重复]

This question already has an answer here:

I expect the following php code to return a null value (echo "no dup" to test this), but instead it detects something (echo "dup"), and I can't figure out why:

$isNameThere = 'SELECT FullName FROM tblStudentSchedules WHERE 
FullName=\'{$studentName}\'';

$duplicate = mysqli_query($con,$isNameThere);
if(empty($duplicate)) { 
echo "no dup";
$addTheName =  'INSERT INTO tblStudentSchedules (FullName) VALUES 
(\'{$studentName}\')';
mysqli_query($con, $addTheName);
} else {
echo "dup ";
} 

The field FullName, and the whole table now, is empty.

</div>

mysqli_query():

"For successful SELECT, SHOW, DESCRIBE, or EXPLAIN queries it will return a mysqli_result object. For other successful queries it will return TRUE. FALSE on failure"

So $duplicate will never be empty and your code will always run the else statement.

if(empty($duplicate)) { // Always not empty.

if($duplicate) {  // This should work.

Try this:

$isNameThere = "SELECT FullName FROM tblStudentSchedules WHERE FullName=\'{$studentName}\'";
$result = mysqli_query($con,$isNameThere);

if(mysqli_num_rows($result)) // count if there are rows affacted
{
    echo "no dup";
    $addTheName = "INSERT INTO tblStudentSchedules (FullName) VALUES (\'{$studentName}\')";
    mysqli_query($con, $addTheName);
}
else 
{
    echo "dup";
} 

Also adding mysqli_error() will be helpful in debugging.

mysqli_query($con, $isNameThere) or die("Query failed: ".mysqli_error($con));

Use fetch_row() to check if there is a result. it will return false if no rows found.

if(!$duplicate->fetch_row()) {
echo "no dup";
$addTheName =  'INSERT INTO tblStudentSchedules (FullName) VALUES (\'{$studentName}\')';
mysqli_query($con, $addTheName);
} else {
echo "dup ";
}