Hi fastsol,
Thank you very much for taking the time to help me with this. I've found a lot useful about your reply, particularly finding a way of inserting multiple values to the database by including the mysqli_query in the foreach.
I've been tinkering around with the code, trying to understand the bits I didn't at first.
I changed (isset($_POST['submit'])) to ($_SERVER["REQUEST_METHOD"] == "POST") as I've seen somewhere that the submit value can be spoofed, so wanted to take the extra precaution that the form was actually being submitted (unless I'm incorrect?).
This is what I'm using now:
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$con = mysqli_connect("localhost","root","","my_database");
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql = $errors = "";
foreach ($_POST['car'] as $car) {
$id = mysql_real_escape_string(trim($car['CarID']));
$title = mysql_real_escape_string(trim($car['CarTitle']));
// detect pairs
if ((strlen($id) > 0) || (strlen($title) > 0)) {
// check for empty input and error
if ((strlen($id) == 0) || (strlen($title) == 0)) {
$errors = "<br />At least one or more pairs has no ID or Title.";
}
// then check for 0-9 only and error
elseif (!preg_match('/^[0-9]*$/', $id)) {
$errors = "<br />Numbers only in ID.";
}
// validation passed, insert to database
else {
$sql="INSERT INTO carids_cartitles (CarID, CarTitle) VALUES ($id, '$title')";
if (!mysqli_query($con,$sql)) {
die('Error: ' . mysqli_error($con));
}
}
}
// end detect pairs
}
// end foreach
mysqli_close($con);
}
?>
<!DOCTYPE HTML>
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<!--<script type="text/javascript">
$(document).ready(function($) {
$('[name="myForm"]').submit(function(event) {
// all form fields empty?
if ($('input:text').filter(function() { return $(this).val().trim().length > 0; }).length == 0) {
event.preventDefault();
$('input:text').css({'border':''});
alert('All form fields empty!');
}
else {
// pair validation
$('form > div').each(function() {
// pair(s) detected
if (($(this).find('input').eq(0).val().trim().length > 0) || ($(this).find('input').eq(1).val().trim().length > 0)) {
$(this).find('input').each(function() {
if ($(this).val().trim().length == 0) {
event.preventDefault();
$(this).css({'border': '1px solid red'});
}
// post-validation clear border if individual input is no longer empty/numeric check passes
else {
$(this).css({'border': ''});
if ($(this).index() === 0) {
if (!$(this).val().match(/^\d*[0-9](|.\d*[0-9]|,\d*[0-9])?$/)) {
event.preventDefault();
$(this).css({'border': '1px solid blue'});
}
}
}
});
}
// end pair(s) detected
// no pair(s) detected
else {
// post-validation clear border if both inputs no longer have values
$(this).find('input').css({'border': ''});
}
// end no pair(s) detected
});
// end pair validation
}
// end all form fields empty?
});
// end submit event
});
// end document ready
</script> -->
<style type="text/css">
input[type="text"] {
height: 20px;
}
input[name*="CarID"] {
width: 65px;
}
input[name*="CarTitle"] {
width: 450px;
}
form > div {
margin-bottom: 4px;
}
.error {
border: 1px solid red;
}
.not_numeric {
border: 1px solid blue;
}
</style>
</head>
<body>
<form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method="post" name="myForm">
<?php
$num = 10;
for($x=0; $x<$num; $x++) {
echo '<div>';
echo '<input type="text" name="car['.$x.'][CarID]" value="" maxlength="20" />';
echo '<input type="text" name="car['.$x.'][CarTitle]" value="" maxlength="175" />';
echo '</div>';
}
?>
<input type="submit" value="submit" name="submit" />
<?php if ($_SERVER["REQUEST_METHOD"] == "POST") { echo $errors; } ?>
</form>
</body>
</html>
I was just wondering, what is the difference between the way you have set the arrays to array_combine? It appears I am able to validate the values just the same. I'm not saying your way is wrong (what do I know!). Just curious and learning
I've been thinking over the past few days what it is I actually want to do. I've come to the conclusion that I'll need to effectively replicate the jQuery validation I've already got but with PHP (I will need to check the CarID against values in the database, if a duplicate is found, show an error).
So I need to apply the following to the PHP validation:
1. Retain all values entered in case validation fails
2. Within a pair of text inputs that has a value, detect which one doesn't have a value and show an error next to that specific input
3. Ensure CarID is 0-9 only with the regex, otherwise show an error next to that specific input
4. Check CarID against database, if same CarID is found on database, show error next to that specific input "CarID already registered!", otherwise insert to database (I'm just looking to get points 1-3 down and learn this myself, the hard way lol).
Firstly I've tried to modify your code to retain values after validation:
echo '<input type="text" name="car['.$x.'][CarID]" value="'.$id.'" maxlength="20" />';
This doesn't work. I know if I wasn't using the foreach to generate the form fields, I could use something like:
<input type="text" name="car[0][CarID]" value="<?php if ($_SERVER["REQUEST_METHOD"] == "POST") { echo $valueofthisid; } ?>" maxlength="20" />
The thing is, the only way I can see of doing it this way is to hard-code 20x inputs, each with their own unique value and error message. I.e. CarID1, CarID2, CarTitle1, CarTitle2, CarID1error1, CarTitle1error1 etc - and that just strikes me as inefficient.
May I ask upon your genius once more? Or do you think it'd have to be done the hard way?