All form fields saving to database regardless of validation

Hi everyone,

I’ve finally bitten the bullet and started to learn PHP! As expected, I’m hitting some road blocks along the way but hope you can help :slight_smile:

I have a form in which the user will be able to enter 10x numeric IDs and 10x alphanumeric Titles.

The issue:

I want only the values that pass validation to be saved to my database, but at the moment, even if my values don’t pass validation, they’re still saved to my database.

Here’s the code (the HTML and PHP is on one page and the form submission is being captured with REQUEST_METHOD). I’m just validating the first ID and first Title to start with (test of concept before replicating code):

[php]
$ID1Err = $Title1Err = “”;
$ID1 = $Title1 = “”;

// form validation
if (empty($_POST[‘ID1’])) {
$ID1Err = “
please enter an ID”;
}
elseif (!is_numeric($_POST[‘ID1’])) {
$ID1Err = “
numbers only”;
}
else {
$ID1 = mysqli_real_escape_string($con, $_POST[‘ID1’]);
}

if (empty($_POST['Title1'])) {
    $Title1Err = "<br /><span class='error'>please enter a Title</span>";
}
	else {
		$Title1 = mysqli_real_escape_string($con, $_POST['Title1']);
	}

// add form field values to database
$sql=“INSERT INTO ids_titles (ID, Title) VALUES (’$ID1’, ‘$Title1’), (’$ID2’, ‘$Title2’), (’$ID3’, ‘$Title3’), (’$ID4’, ‘$Title4’), (’$ID5’, ‘$Title5’), (’$ID6’, ‘$Title6’), (’$ID7’, ‘$Title7’), (’$ID8’, ‘$Title8’), (’$ID9’, ‘$Title9’), (’$ID10’, ‘$Title10’)”;
[/php]

I’ve got a funny feeling this is a rookie error but the simple solution is escaping me (no PHP-pun intended!). At a guess I’d say I need to populate the SQL values with only the form field variables that pass validation?

You’re making things more complicated than they need to be:

[php] if (empty($_POST[‘ID1’])) {
$error[‘id’] = “
please enter an ID”;
}[/php]

Just check to see if the user input is valid, it is then you know you can’t proceed. Don’t use else if (I think that is referred to as nested if statements).

Then when you are ready to store the data (if it’s valid) simply do something like this (Sorry I was using some really old code, this code can be tighten up a lot):

[php]<?php
$errMsg[] = NULL;
$error = NULL;
//$errMsg[0] = ‘This error 1!’;
// error = “ERROR”; // Set Condition Error;
//$errMsg[1] = ‘This error 2!’;
// error = “ERROR”; // Set Condition Error;
//print_r($errMsg);

if ($error !== NULL) {
// Display Error Message(s):
foreach ($errMsg as $value) {
echo ‘

’ . $value . ‘

’;
}
} else {
echo ‘Success’;
// Store data to table in database:
}[/php]

I personally think it’s easier to check the form validation on the client side by using JavaScript or a JavaScript Library such as jQuery. The only validation on the server side probably would be a username or data where you can’t have duplication in the database table(s).

Thank you Strider64, I’m still a bit new but some things are becoming clearer.

To be honest I should’ve made myself clearer, my main aim is to:

  1. Detect if all form fields are empty and show an error.
  2. Grab CarIDs and CarTitles in arrays (I have now done this by naming the form fields all CarID[] and CarTitle[] so they pass as an array when the script runs).
  3. Each CarID should be associated with each CarTitle between the two arrays (to “pair” them together).
  4. Validate pairs as follows:
    a) For any pair, if CarID and CarTitle = empty, ignore further validation and don’t save to the database (it didn’t seem like I needed to code this requirement, instead opted to validate only on if one of the values is present as below).
    b) Identify pairs to validate/save to the database as follows:
    a) If CarID or CarTitle has a value, validate:
    a) Ensure that both fields have a value (display error in field that does not have a value).
    b) Ensure ID is numeric (display error in field that does not have a numeric value).
    c) Once both fields have a value, and ID has a numeric value, save to the database.

I’ve been digging around the web to come up with this:

[php]
// declare variables for validation
$CarID = $_POST[‘CarID’];
$CarTitle = $_POST[‘CarTitle’];
$error1 = $error2 = $success = “”;

// validation

// if none of the form fields have been filled in:
if (empty($CarID) && empty($CarTitle)) {
$error1 = “All form fields are empty! Form NOT submitted!
”;
}
else {
// combine arrays and validate values of each array as pairs (each ID in the first array should be associated with the corresponding Title in the second array)
foreach (array_combine($CarID, $CarTitle) as $ID => $Title) {
// check which field of each pair is empty (if any) and display error:
if (empty($ID) || empty($Title)) {
$error2 = “empty!”;
}
// assuming each pair has a value, ensure ID only contains numbers:
elseif (!is_numeric($ID)) {
$error2 = “numbers only!”;
}
else {
// validation passed! insert validated values into database table using mysqli_real_escape_string. How do I do this?
$success = “
VALIDATION PASSED, FORM (NOT REALLY) SUBMITTED!”;
}
}
}
[/php]

I know you said not to use elseif, sorry. I was writing this before I saw your reply. I need to write it in a way I can understand, even if that means bulk code, later when I’m more familiar with what I’m doing I’ll start looking for more efficient ways.

Anyway, the above script isn’t working as intended (no surprise). The first “if” block doesn’t run if I click SUBMIT without filling in any of the form fields.

What happens is, all the form fields are populated with “empty!”, probably because I’ve included the PHP error in all the form fields values, but it should only be showing the error in the affected form fields based on the validation for the pairs.

Likewise, if I enter letters in a CarID field, all the form fields are populated with “numbers only!”.

I’ve been staring at code too long today… sorry if I’m not making any sense!

Its insert regardless of validation because you’re not telling it to stop if there’s an error, you have the error messages being printed out hopefully.

try this:[php]
if (empty($_POST[‘ID1’])) {
$ID1Err = “
please enter an ID”;
} elseif(!is_numeric($_POST[‘ID1’])) {
$ID1Err = “
numbers only”;
} else {
$ID1 = mysqli_real_escape_string($con, $_POST[‘ID1’]);
}

if (empty($_POST['Title1'])) {
	$Title1Err = "<br /><span class='error'>please enter a Title</span>";
} else {
	$Title1 = mysqli_real_escape_string($con, $_POST['Title1']);
}

if!$ID1Err && !$Title1Err) {
	// add form field values to database
	$sql="INSERT INTO ids_titles (ID, Title) VALUES ('$ID1', '$Title1'), ('$ID2', '$Title2'), ('$ID3', '$Title3'), ('$ID4', '$Title4'), ('$ID5', '$Title5'), ('$ID6', '$Title6'), ('$ID7', '$Title7'), ('$ID8', '$Title8'), ('$ID9', '$Title9'), ('$ID10', '$Title10')";
}

}[/php]

Sponsor our Newsletter | Privacy Policy | Terms of Service