-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

3
  • 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 Commented Nov 25, 2019 at 3: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 <select> and input text, every select is related to the input text with the bank account number, I will update the question with full code Commented Nov 25, 2019 at 5:20
  • Warning: You are wide open to SQL Injections and should use parameterized prepared statements instead of manually building your queries. They are provided by PDO or by MySQLi. 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. Escaping is not enough! Commented Dec 1, 2019 at 12:43

1 Answer 1

-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);
?>
Sign up to request clarification or add additional context in comments.

2 Comments

Warning: You are wide open to SQL Injections and should use parameterized prepared statements instead of manually building your queries. They are provided by PDO or by MySQLi. 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. Escaping is not enough!
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?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.