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

1 php mysql

如何根据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.";
}
Run Code Online (Sandbox Code Playgroud)

$ maritalStatus ==“ yes”不会返回true,即使这恰好是该单元格中的值。

Pas*_*TIN 5

如果要处理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.";
    }
}
Run Code Online (Sandbox Code Playgroud)


如果这样做没有帮助,请检查以下内容:

  • 如果查询实际返回结果
  • 如果这些结果实际上是您认为的那样。

可以使用来完成此操作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
}
Run Code Online (Sandbox Code Playgroud)



作为旁注,您在评论中说,回显$ maritalStatus可以使您获得Yes

如果Y您的数据库中有一个大写字母,那就是代码失败的原因:您正在yes以小写字母测试“ ”。

在PHP中,使用==运算符进行字符串比较时,大写字母和小写字母被视为不同的字符

如果要以不区分大小写的方式进行比较,则必须: