Question

Ok, I have a problem with the following insert statement: (Tell me if you want the whole code)

$required = array('exam_id', 'subject', 'exam_date');

$error = false;
foreach($required as $field) {
    if ( !empty($_POST['insert'])) {
        $InsertQuery = "INSERT INTO Exam (exam_id, subject, exam_date) VALUES 
                        ($_POST[uexam_id],$_POST[usubject],$_POST[uexam_date])";
        $result = mysql_query($InsertQuery, $con);
        if (!$result) { $error = true; }
    }
} 
if ($error) {
    die ("All fields are required! <a href='examisud.php'> Back to Form </a>");
}

Ok, so essentially I want all fields (exam, subject & exam_date) to be required fields. If the user doesn't fill in a field, an error pops up asking them to go back and refill all fields). In that way, it works. However, when I test it and fill in all fields, the error also pops up too, so regardless of what happens, the insert isn't working correctly and any attempts so far i've made to change it result in fields being inserted into, but the validation no longer works. Any help would be most appreciated!

Was it helpful?

Solution

You're trying to run 3 queries instead of trying to run the query after the test...

$required = array('uexam_id', 'usubject', 'uexam_date');

$error = false;
//first check all required fields are not empty. if post has values
if(!empty($_POST))
{
    foreach($required as $field) 
        if ( empty($_POST[$field])) 
            $error = true;           
    //a field was empty, show error
    if ($error) {
        die ("All fields are required! <a href='examisud.php'> Back to Form </a>");
    }
    //no error - try the query
    else
    {
        $InsertQuery = "INSERT INTO Exam (exam_id, subject, exam_date) VALUES 
                        ($_POST[uexam_id],$_POST[usubject],$_POST[uexam_date])";
        $result = mysql_query($InsertQuery, $con) or die('query Failure:'. mysql_error());
    }
}

Also as a side note as im sure others will mention, mysql is deprecated, please look to using mysqli in the future. Also I notice the required fields don't have the 'u' before them as the query does. I assume this is a mistake?

OTHER TIPS

Keep everything else the same but add a break statement as follows:

//Previous code, then

        if (!$result) { $error = true; }
    break;
    }
}
if ($error) {
    die ("All fields are required! <a href='examisud.php'> Back to Form </a>");
}

Your foreach loop may continue to run without a break statement, so even after a successful query (all 3 fields filled, and $error = false), if the query of the next iteration fails, now $error = true, hence the execution of "die".

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top