This question already has an answer here:
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);
</div>
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();