PHP为什么!空无效?

时间:2011-01-19 05:46:59

标签: php mysql

!空代码在此代码中起作用:

if (!empty($p1_firstname))
mysql_query ("INSERT INTO cases VALUES ('','$case','$date_booked','$p1_firstname','$p1_lastname','$city')");

if (!empty($p2_firstname)) 
$register_case = mysql_query ("INSERT INTO cases VALUES ('','$case','$date_booked','$p2_firstname','$p2_lastname','$city')");

但不是这段代码:

if (!empty($p1_firstname))
$passenger1 = 1;
mysql_query ("INSERT INTO cases VALUES ('','$case','$passenger1','$date_booked','$p1_firstname','$p1_lastname','$city')");

if (!empty($p2_firstname)) 
$passenger2 = 2;
$register_case = mysql_query ("INSERT INTO cases VALUES ('','$case','$passenger2','$date_booked','$p2_firstname','$p2_lastname','$city')");

即使字段为空,它仍会执行查询。可以做些什么来解决这个问题?

1 个答案:

答案 0 :(得分:8)

因为你缺少大括号

if (!empty($p1_firstname)) {
    $passenger1 = 1;
    mysql_query ("INSERT INTO cases VALUES ('','$case','$passenger1','$date_booked','$p1_firstname','$p1_lastname','$city')");
}

if (!empty($p2_firstname)) {
    $passenger2 = 2;
    $register_case = mysql_query ("INSERT INTO cases VALUES ('','$case','$passenger2','$date_booked','$p2_firstname','$p2_lastname','$city')");
}

如果条件满足,则缺少花括号表示if执行后只有立即语句。 mysql_query()调用根本不属于if块,无论您的变量是否为empty(),都会执行。

通过省略大括号而不是正确地缩进代码,这种错误变得更难以发现。并不是说你不能这样做,但它更安全,并且浪费更少的时间,采用良好压痕的习惯,并使用花括号清楚地表明控制流程块。