Inserting Multiple Rows with a Single Prepared Statement in MySQLi
Problem:
Insert multiple rows into a database using a prepared statement, avoiding the need for separate queries for each row.
Solution:
While prepared statements typically handle single row operations, it's possible to insert multiple rows using a special query syntax and methodology.
Approach:
Code Example:
<code class="php">$rows = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]; $rowCount = count($rows); $values = "(&" . implode('),(', array_fill(0, $rowCount, '?,?,?')) . "&)"; $stmt = $conn->prepare("INSERT INTO test (col1, col2, col3) VALUES $values"); $stmt->bind_param(str_repeat('i', $rowCount * 3), ...array_merge(...$rows)); $stmt->execute();</code>
Alternative Approach:
It's also acceptable to use a prepared statement with a single row of placeholders and execute it in a loop for each row, which is simpler but potentially less efficient.
The above is the detailed content of How to Insert Multiple Rows with a Single Prepared Statement in MySQLi?. For more information, please follow other related articles on the PHP Chinese website!