如何根据 mysql 表单元格的值执行 if 语句。例如,我有一张人员表,其中有一列名为 marital_status。此列具有两个值之一:是或否。但这不起作用:
$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"不会返回 true,即使这正是该单元格中的值。
最佳答案
如果你想处理 SQL 查询返回的每一行数据,你应该将你的条件放在 while
循环中——它遍历查询执行返回的行:
$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.";
}
}
如果这没有帮助,检查一下可能会有用:
- 如果查询确实返回结果
- 如果这些结果确实如您所想。
这可以使用 var_dump
来完成, 转储变量的内容。例如,在您的情况下,您可以使用:
$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
}
作为旁注,您在评论中说回显 $maritalStatus 会让您“Yes
”。
如果您的数据库中有大写的 Y
,这就是您的代码失败的原因:您正在测试“yes
”小写。
在 PHP 中,使用 ==
运算符进行字符串比较,将大写字母和小写字母视为不同的字符。
如果您想以不区分大小写的方式进行比较,您必须:
- 将所有字符串转换为相同的大小写(大写或小写,由您选择)
- 参见
strtolower
或strtoupper
- 或
mb_strtolower
/mb_strtoupper
如果使用多字节编码,例如 UTF-8
- 参见
- 使用不区分大小写的比较函数,例如
strcasecmp
关于php - 如何根据 MySQL 表单元格的值执行 IF 语句?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2546906/