开发者

PHP Why is !empty not working?

!empty works in this code:

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')");

but not this code:

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')");

It still does the query even if the field is empty. What can be done to fix this?


Because you're missing curly braces

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')");
}

The missing curly braces mean only the statement immediately following the ifs get executed if their conditions are satisfied. The mysql_query() calls are not part of the if blocks at all, and will execute regardless of whether your variables are empty() or not.

By both omitting the braces and not indenting your code correctly, this kind of error becomes even harder to spot. Not that you can't do that, but it's much safer, and results in less time wasted, to adopt a habit of good indentation and using curly braces to clearly indicate control flow blocks.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜