multiple SQL insertion & form validation In php
-
27-10-2019 - |
Question
I am trying to do multiple product add with a form using php and mysql , and i am confusing on the concept of doing these,
My expecting output is , provide a form with at least ten rows of multiple field to be fill and do the validation among these , and proceed to insertion if no error .
Here is what i understand about single form insertion so far:
$add_errors = array();
//if there is a post request
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
// do some validation
if (empty($_POST['name'])) {
$add_errors['name'] = 'Please enter the name!';
}
if (empty($_POST['description'])) {
$add_errors['description'] = 'Please enter the description!';
}
if (empty($add_errors)) { // If everything's OK.
//do the insertion
$q = 'INSERT INTO ........')';
}
}//end of form submission
echo '<form action="product_add.php" enctype="multipart/form-data" method="post" accept-charset="utf-8">';
echo '<input type=..... name=...... id=.....>';
echo '<input type=..... name=...... id=.....>';
echo '<input type=..... name=...... id=.....>';
echo '</form';
//this form is only a single row with multiple column(field) ,I am trying to make it into multiple column
Solution
I would rewrite the above code...I'm going to rewrite it here:
<?php
$rows = 10; // rows desired.
//if there is a post request
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
while($i < $rows){
if (empty($_POST['description'.$i])) {
$add_errors['description'.$i] = 'Please enter the description!';
}
// more error checking if needed...
++$i;
}
if (empty($add_errors)) { // If everything's OK.
//do the insertion
$q = 'INSERT INTO ........')';
}
}//end of form submission
echo '<form action="product_add.php" enctype="multipart/form-data" method="post" accept-charset="utf-8">';
$i = 0;
while($i < $rows){
echo '<input type=..... name="description'.$i.'" id=.....>';
++$i;
}
echo '</form';
?>
Try something like that...(my code might have an error or two in it as I just wrote it here and didn't test it) but that's the general idea. =)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow