如何根据MySQL表格单元格的值进行IF语句?

How can I do an if statement based on the value of a mysql table cell. For example, I have a table of people with a column called marital_status. This column has one of two values: yes or no. But this doesn't work:

$query = mysql_query("SELECT marital_status FROM people WHERE first_name = 'John'");

while ($row = mysql_fetch_assoc($query)) {

     $maritalStatus = $row['marital_status'];

}

if ($maritalStatus == "yes") {
   echo "This person is married.";
}
else {
   echo "This person is NOT married.";
}

$maritalStatus == "yes" doesn't return as true even though that is exactly the value in that cell.

If you want to work on each line of data returned by your SQL query, you should place your condition inside the while loop -- which iterates over the lines returned by the excution of the query :

$query = mysql_query("SELECT marital_status FROM people WHERE first_name = 'John'");

while ($row = mysql_fetch_assoc($query)) {
    $maritalStatus = $row['marital_status'];
    if ($maritalStatus == "yes") {
       echo "This person is married.";
    }
    else {
       echo "This person is NOT married.";
    }
}


If this doesn't help, it could be useful to check :

  • If the query actually returns results
  • If those results are actually what you think they are.

This can be done using var_dump, to dump the content of a variable. For example, in your situation, you could use :

$query = mysql_query("SELECT marital_status FROM people WHERE first_name = 'John'");
while ($row = mysql_fetch_assoc($query)) {
    var_dump($row);     // Will display the content of $row
}



As a sidenote, you said in a comment that echoing $maritalStatus gets you "Yes".

If there is a Y in uppercase in your database, that's the reason why your code fails : you are testing for "yes" in lowercase.

In PHP, using the == operator for string comparisons, uppercase letters and lowercase letters are considered as different characters.

If you want to compare in a case-insensitive manner, you'll have to either :

You should move your if block inside the while loop.
And make sure you account for letters case.

$query = mysql_query("SELECT marital_status FROM people WHERE first_name = 'John'");

while ($row = mysql_fetch_assoc($query)) {

     $maritalStatus = strtolower($row['marital_status']);

    if ($maritalStatus == "yes") {
      echo "This person is married.";
    }
    else {
      echo "This person is NOT married.";
    }
}