I use a very simple insert statement
INSERT INTO table (col1, col2, col3) VALUES (1,2,3), (4,5,6), (7,8,9), ...
Currently, the part of the query that holds the values to be inserted is a separate string constructed in a loop.
How can I insert multiple rows using a prepared statement?
edit: I found this piece of code. However, this executes a seperate query for every row. That is not what I am looking for.
$stmt = $mysqli->stmt_init();
if ($stmt->prepare("INSERT INTO table (col1, col2, col3) VALUES (?,?,?)")){
$stmt->bind_param('iii', $_val1, $_val2, $_val3);
foreach( $insertedata as $data ){
$_val1 = $data['val1'];
$_val2 = $data['val2'];
$_val3 = $data['val3'];
$stmt->execute();
}
}
edit#2: My values come from a multidimensional array of variable length.
$values = array( array(1,2,3), array(4,5,6), array(7,8,9), ... );
This is normally only a technique that I use when I am writing a prepared statement for a query that contains an IN
clause. Anyhow, I've adapted it to form a single prepared query (instead of iterated prepared queries) and I tested it to be successful on my server. The process is a bit convoluted and I don't know if there will ever be any advantage in speed (didn't benchmark). This really isn't the type of thing that developers bother with in production.
Code:
if (!$mysqli = new mysqli($config[0], $config[1], $config[2], $config[3])) {
echo "connection bonk";
} else {
$array = [[1, 2, 3],[4, 5, 6], [7, 8, 9]]; // sample indexed array of indexed arrays
$params = [];
foreach ($array as $row) {
$parentheticals[] = '('.implode(',', array_fill(0, sizeof($row), '?')).')'; // build parentheticals
$params = array_merge($params, $row); // flatten actual values to 1-dim array
}
$values = implode(',', $parentheticals);
$count = sizeof($params); // assuming you have balanced subarrays
if ($stmt = $mysqli->prepare("INSERT INTO test (col1, col2, col3) VALUES $values")) {
array_unshift($params, str_repeat('i', $count)); // prepend the type values string
$ref = []; // add references
foreach ($params as $i=>$v) {
$ref[$i] = &$params[$i]; // pass by reference as required/advised by the manual
}
call_user_func_array([$stmt, 'bind_param'], $ref);
if ($stmt->execute()) {
echo $stmt->affected_rows , " affected rows"; // how many rows were inserted
} else {
echo "execution bonk";
}
$stmt->close();
} else {
echo "prepare bonk";
}
}