0

!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?

1
  • 1
    PS. You should use PDO(net.tutsplus.com/tutorials/php/…) because if you don't escape your queries your site will be vulnerable to SQL-injections! PDO has prepared statements which protect you against this! Commented Jan 19, 2011 at 5:57

1 Answer 1

8

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.