How to insert multiple arrays using PDO from a PHP form?

0

Hi, I have a code that works to insert multiple records but only one array, I plan to add more inouts with different arrays but I can not find how to modify the part of the arrays. I imagine that in the case of the sql it would be something like this:

$insertStmt = $db->prepare("INSERT INTO productos (producto, id, etc) VALUES (:field, :id, etc)");

Correct me if I'm wrong

if(isset($_POST['btn-add']))
    {
        $fields= (is_array($_POST['fields'])) ? $_POST['fields'] : array();
        $insertStmt = $db->prepare("INSERT INTO productos (producto) VALUES (:field)");

        foreach ($fields as $field) {
            $insertStmt->execute(array('field' => $field));
        }

                                        header("Location: productos.php");

    }
    ?>

So I have my input:

 $(container).append('<input type=text required="required" name ="fields[]" class="input" id=tb' + iCnt + ' ' +
    'placeholder="Producto ' + iCnt + '" />');
    
asked by Daniel Treviño 29.08.2017 в 18:27
source

1 answer

0

First of all I would not do an execute for every $field that there is in $fields .

What you can do is the following:

// el insert permite añadir una lista de valores 
// INSERT INTO tbl_name (a,b,c) VALUES (1,2,3),(4,5,6),(7,8,9);
$query = "insert into productos (col1, col2, col3) values "

for($i = 0; $i < sizeOf($fields); $i++){
   $query .= "?, "
}

// para borrar útlima comma haces un 

$query = rtrim($query, ',');

$stmt = $db->prepare($query); 

// el numero de interogante = sizeOf($fields)
// los interogantes puedes hacer dinamicos con un bucle foreach

// count empieza desde 1
$count = 1;
foreach ($fields as $field) {
  $db->bindParam($count, $field);
  $count++;
}

// finalement ejecutas 
$db->execute()
    
answered by 29.08.2017 в 22:18