Insert 'N' times of records with the same inputs

0

Good afternoon, I would like to know where my error is, since what you said above does not work for me. I placed a print_r and it gives me the following result ...

 INSERT INTO trafos (centro) VALUES ('1')INSERT INTO trafos (centro) VALUES ('2')INSERT INTO trafos (centro) VALUES ('3')

that is, it theoretically captures it, but when it is saved in the bdd it only saves 1

<?php  

    $cantidadI=3;
    include_once('conexion.php');

    $centro =$_POST['centro'];

    foreach ($_POST['centro'] as $key=>$values) 
        { 
            $guardar="INSERT INTO trafos (centro) VALUES ('".$values['centro']."')";
            $result=mysql_query($guardar);
            mysql_close();
        }
 ?>

<div id="contenedor">

    <form id="datos" method="post" action="#">

    <div id="tabla" class="form-group">
            <table>
                <?php 

                    for ($i=1; $i<=$cantidad; $i++) { 
                ?>
                        <tr>
                            <td colspan="4" align="center">
                                <input id="centro" name="centro[<?php $i ?>][centro]" value="" type="text" />
                            </td>
                        </tr>
                <?php
                    } 
                ?>
            </table>
            <br>
        </div>
        <input id="guarda"  type="submit" name="guarda" value="Guardar" />
        <input id="cance"   type="button" name="cance"  value="Cancelar" />
    </form>
</div>
    
asked by Jorge Daniel Galati 26.12.2017 в 23:49
source

1 answer

2

hello seeing your code the only thing you have wrong is the way to insert the data in the bd look, here is a basic example of how you should do it:

INSERT INTO table_name (column1, column2, column3,...)
VALUES (value1, value2, value3,...)

and the error that I also see is that you did not add the ++ in the foreach, look at a foreach is:

The foreach constructor provides a simple way to iterate over arrays. foreach works only on arrays and objects, and will throw an error when trying to use it with a variable of a different type of data or an uninitialized variable. There are two syntaxes:

foreach (expresión_array as $valor)
    sentencias
foreach (expresión_array as $clave => $valor)
    sentencias
    

more information: PHP manual

and what you need to add is something like this:

if (isset($_POST['submit'])) {

$i = 0;
foreach ($_POST as $val) {
    $name = $_POST['name'][$i];
    $age = $_POST['age'][$i];

    mysql_query("INSERT INTO users (name, age) VALUES ('$name', '$age')");
    $i++;
  } 
}

You only need to adapt it to yours and if you want more about the previous code you can see the question in Stackoverflow in English: question in english

    
answered by 27.12.2017 в 00:02