-1

I have a form with dynamic inputs, in this case, I take a car owner with multiple cars, so for the same person/client I need to save several cars with the brand name and year model:

<form action="save.php" method="post">
    <label for="name">Name of owner</label>
    <input type="text" name="name" id="name">
<div class="field_wrapper"> <!--wrapper that help me in the javascript button-->
    <label for="car_model">Brand name</label>
    <select name="car_model[]" id="car_model">
        <option value="ford">Ford</option>
        <option value="honda">Honda</option>
        <option value="chevrolet">Chevrolet</option>
    </select>
    <label for="year">Year</label>
    <input type="number" name="year[]" id="year">
    <input type="button" class= "add_button" value="+" onClick="javascript:void(0);" title="add fields" style="width:25px"></td>
</div>
</form>

I don't know how many cars he/she have, so I used this javascript for add and remove input fields with jQuery:

<script type="text/javascript">
    $(document).ready(function(){
    var maxField = 5; //Input fields increment limitation
    var addButton = $('.add_button'); //Add button selector
    var wrapper = $('.field_wrapper'); //Input field wrapper
    var fieldHTML = '<div><label for="car_model">Brand name</label><select name="car_model[]" id="car_model"><option value="ford">Ford</option><option value="honda">Honda</option><option value="chevrolet">Chevrolet</option></select><label for="year">Year</label><input type="number" name="year[]" id="year"><input type="button" class= "remove_button" value="-" onClick="javascript:void(0);" title="remove field" style="width:25px"></div>'; //New input field html 
    var x = 1; //Initial field counter is 1
    $(addButton).click(function(){ //Once add button is clicked
        if(x < maxField){ //Check maximum number of input fields
            x++; //Increment field counter
            $(wrapper).append(fieldHTML); // Add field html
        } else{
            alert('you reach the limit')
        }
        });
        $(wrapper).on('click', '.remove_button', function(e){ //Once remove button is clicked
            e.preventDefault();
            $(this).parent('div').remove(); //Remove field html
            x--; //Decrement field counter
            });
        });
</script>

What is my goal? in some cases I will have multiple inputs for the same "name" value, So I save the brand name as a array car_model[] and year[]. I understand that I must save in my save.php something like this:

$name=$_POST['name'];
$array_car=$_REQUEST['car_model'];
$array_year=$_REQUEST['year']

Here comes the problem: how do I save that in my database? I try with a foreach but looks like is not the rigth way to do it. Note: I know how to save a "regular" form, I mean, it would be something like:

$query="INSERT INTO cars ('name','car_model','year') VALUES ('$name','$car_model','$year')";

and variables should be:

$name=$_POST['name'];
$car_model=$_POST['car_model'];
$year=$_POST['year'];

but, what about this time? thanks for help, and I hope this time I explain what I need on a better way

  • I have two questions, why are you post both data as array? and why are you using `foreach` on the back-end side? could you show the overall codes or describe what is your goal – Hasta Dhana Nov 25 '19 at 03:55
  • Actually I don't know which is the right function to use at backend, foreach was the closest that I found. Let me try to resume, I have a form with several inputs, but a couple of fields need to be nested, why? Because they come from a dynamic input, I'm doing a complaint form, in the same complaint form could be more than just one bank account, and for each bank account is a number related. So, when I click on a button (JavaScript used) it adds a new – Andrewfreites Nov 25 '19 at 05:20
  • **Warning:** You are wide open to [SQL Injections](https://php.net/manual/en/security.database.sql-injection.php) and should use parameterized **prepared statements** instead of manually building your queries. They are provided by [PDO](https://php.net/manual/pdo.prepared-statements.php) or by [MySQLi](https://php.net/manual/mysqli.quickstart.prepared-statements.php). Never trust any kind of input! Even when your queries are executed only by trusted users, [you are still in risk of corrupting your data](http://bobby-tables.com/). [Escaping is not enough!](https://stackoverflow.com/q/5741187) – Dharman Dec 01 '19 at 12:43

1 Answers1

-2

First, save each array and values that you receive from POST

$name=$_POST['name'];
$array_car=$_REQUEST['car_model'];
$array_year=$_REQUEST['year'];

use sizeof() to measure the array size and save it to a variable, no matter which one because both will have the same size: $size=sizeof($array_car); then use a for loop limit by the size, and finally, the code will look like this:

<?php
include 'conexion.php';
$name=$_POST['name'];
$array_car=$_REQUEST['car_model'];
$array_year=$_REQUEST['year'];
$size=sizeof($array_car);
for($i=0;$i<$size;$i++){
    $query="INSERT INTO cars (owner,brand,year) VALUES ('$name','$array_car[$i]','$array_year[$i]')";
    if (mysqli_query($conn, $query)) {  
        } else {
            echo "Error: " . $query . "<br>" . mysqli_error($conn);
        }
}
mysqli_close($conn);
?>
  • **Warning:** You are wide open to [SQL Injections](https://php.net/manual/en/security.database.sql-injection.php) and should use parameterized **prepared statements** instead of manually building your queries. They are provided by [PDO](https://php.net/manual/pdo.prepared-statements.php) or by [MySQLi](https://php.net/manual/mysqli.quickstart.prepared-statements.php). Never trust any kind of input! Even when your queries are executed only by trusted users, [you are still in risk of corrupting your data](http://bobby-tables.com/). [Escaping is not enough!](https://stackoverflow.com/q/5741187) – Dharman Dec 01 '19 at 12:43
  • It is a very bad idea to use `die(mysqli_error($conn));` in your code, because it could potentially leak sensitive information. See this post for more explanation: [mysqli or die, does it have to die?](https://stackoverflow.com/a/15320411/1839439) – Dharman Dec 01 '19 at 12:43