开发者

How to do an IF statement based on the value of a MySQL table cell?

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 colu开发者_JAVA百科mn 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 :

  • Convert all strings to the same case (upper or lower, up to you to choose)
    • see strtolower or strtoupper
    • or mb_strtolower / mb_strtoupper if using a multi-byte encoding, such as UTF-8
  • Use a case-insensitive comparison function, such as strcasecmp


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.";
    }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜