Key K Key K - 4 months ago 9
PHP Question

How I can add Multiple values from texboxes with the same name?

Im trying to find a solution to add multiple values in my database using the same name of textboxes but I cant. I dont know exactly if there is and solution
Please see the below code.

<form action="" method="post">
<?php
if(isset($_POST['pats'])){
$pats = $_POST['pats'];
mysql_query("INSERT INTO trainings(pats) VALUES ('$pats')") or die(mysql_error());
}
?>
<input type="text" name="pats" placeholder="Pats">
<input type="text" name="pats" placeholder="Pats">
<input type="text" name="pats" placeholder="Pats">
<input type="text" name="pats" placeholder="Pats">
<input type="text" name="pats" placeholder="Pats">
<input type="submit" name="insert" value="Add">
</form>

Answer

Add the [] to the name attribute of your input elements, they will then get send as an array to the server.

If you want to add the values in different rows:

In your backend you can then iterate over the array you received, check if there are actually values on the corresponding key and insert it into your database.

I added mysql_real_escape_string(), but you should not use this code, as it is still vulnerable to sql injections. See this answer: http://stackoverflow.com/a/60496/3595565

<form action="" method="post">
        <?php
        if(isset($_POST['pats'])){
            foreach ($_POST['pats'] as $pats) {
                if(!empty($pats)){
                    mysql_query("INSERT INTO trainings(pats) VALUES ('" . mysql_real_escape_string($pats) . "')") or die(mysql_error());
                }
            }
        }
        ?>
        <input type="text" name="pats[]" placeholder="Pats">
        <input type="text" name="pats[]" placeholder="Pats">
        <input type="text" name="pats[]" placeholder="Pats">
        <input type="text" name="pats[]" placeholder="Pats">
        <input type="text" name="pats[]" placeholder="Pats">
        <input type="submit" name="insert" value="Add">
</form>