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)
- Use a case-insensitive comparison function, such as
strcasecmp