Reputation: 13
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.
Upvotes: 1
Views: 3809
Reputation: 401022
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.";
}
}
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 :
strtolower
or strtoupper
mb_strtolower
/ mb_strtoupper
if using a multi-byte encoding, such as UTF-8strcasecmp
Upvotes: 5
Reputation: 17608
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.";
}
}
Upvotes: 1