0

I have tried to insert multiple rows but got empty rows in database and other errors. So,tried to use implode (as a better alternative?) but must be doing something wrong here.

$sql = array(); 
    foreach($_POST as $key => $value ) {
        $sql[] = '("'.sqlite_escape_string($key['cust_name']).'", '.$key['address'].')';
    }

    $stmt = $db->prepare('INSERT INTO customers VALUES (cust_name, address) '.implode(','. $sql));
    $stmt->execute($sql); 
  • Not sure if you can do this type of preparation with `PDO`. If you can, you're going to need some more code. – Kermit May 20 '13 at 19:33
  • aha so what should I do instead, that's close to this? – user2402963 May 20 '13 at 19:39
  • Probably do a search since there are multiple questions for this...[PDO Prepared Inserts multiple rows in single query](http://stackoverflow.com/questions/1176352/pdo-prepared-inserts-multiple-rows-in-single-query) – Kermit May 20 '13 at 19:40

1 Answers1

0

Would it be better to do something like the following?

<?php

$into = "";
$values = "";

$cnt = 0;
$post_cnt = count($_POST);
foreach($_POST as $key => $value) {
    $into .= sqlite_escape_string($key).($cnt < $post_cnt && $post_cnt > 1 ? ", ": "");
    $values .= "'".sqlite_escape_string($value)."'".($cnt < $post_cnt && $post_cnt > 1 ? ", ": "");
    $cnt++;
}
$sql = "INSERT INTO customers (".$into.") VALUES (".$values.");";

$stmt = $db->prepare($sql);
$stmt->execute();