Optimizing Mass INSERT Operations in MySQLi: A Secure and Efficient Approach
Inserting large volumes of data into a MySQL database requires a technique that ensures both security and performance. This article explores a method for efficiently inserting numerous rows into a table while mitigating the risk of SQL injections.
The provided code, which utilizes multiple prepared statements inside a loop, can introduce a performance bottleneck and potential stack overflow issues. A better approach is to place the inserts within a transaction and move the prepared statement and parameter binding outside the loop.
$mysqli->query("START TRANSACTION"); $query = "INSERT INTO table (link) VALUES (?)"; $stmt = $mysqli->prepare($query); $stmt->bind_param("s", $one); foreach ($array as $one) { $stmt->execute(); } $mysqli->query("COMMIT");
Transactions provide several advantages for bulk inserts:
In performance tests, moving the inserts into a transaction resulted in a significant speed increase. For 10,000 iterations, the execution time dropped from 226 seconds without transactions to a mere 2 seconds with transactions.
This approach provides a secure and efficient mechanism for inserting large datasets into a MySQL database while mitigating the potential risks of SQL injections and performance bottlenecks.
The above is the detailed content of How Can I Securely and Efficiently Perform Mass INSERT Operations in MySQLi?. For more information, please follow other related articles on the PHP Chinese website!