← Back to PHP Course | Chapter 11: Database | Lesson 14 of 21

PHP MySQL Insert Multiple

एक loop में rows एक-एक करके insert करना काम करता है, लेकिन एक साथ कई rows add करते समय हर single row के लिए एक अलग query चलाना धीमा है -- जैसे सौ products की एक CSV import करना। MySQL एक single INSERT statement में कई rows insert करना support करता है, जो looping से dramatically तेज़ है।
Syntax
php
INSERT INTO table_name (column1, column2)
VALUES (value1a, value2a),
       (value1b, value2b),
       (value1c, value2c);

Basic Multi-Row INSERT Syntax

एक single INSERT statement commas से separated कई parenthesized value groups शामिल कर सकता है -- INSERT INTO users (name, email) VALUES (Sam, '[email protected]'), (Alex, '[email protected]') database को एक call में दो rows insert करता है।

उदाहरण: Basic Multi-Row INSERT Syntax

php
<?php
// Create a new `SQLite3` instance with ':memory:', stored in `$db`
$db = new SQLite3(':memory:');
$db->exec("CREATE TABLE users (name TEXT, email TEXT)");
$db->exec("INSERT INTO users (name, email) VALUES ('Sam', '[email protected]'), ('Alex', '[email protected]')");
// Print `$db->changes() . " rows inserted"` to the output
echo $db->changes() . " rows inserted";
?>

एक Multi-Row INSERT Dynamically बनाना

जब insert की जाने वाली rows data के एक array (जैसे parsed CSV rows) से आती हैं, आप array पर loop चलाकर और resulting value groups को commas से जोड़कर VALUES clause dynamically बना सकते हैं, एक पूरा multi-row INSERT statement produce करते हुए।

उदाहरण: Building a Multi-Row INSERT Dynamically

php
<?php
// Declare `$rows` as an array: `[['Sam', '[email protected]'], ['Alex', '[email protected]']]`
$rows = [['Sam', '[email protected]'], ['Alex', '[email protected]']];
$values = array_map(function ($r) {
    // Return `"('" . $r[0] . "', '" . $r[1] . "')"` from this function
    return "('" . $r[0] . "', '" . $r[1] . "')";
}, $rows);
// Declare `$sql`, set to `"INSERT INTO users (name, email) VALUES " . implode(", ", $values)`
$sql = "INSERT INTO users (name, email) VALUES " . implode(", ", $values);
// Print `$sql` to the output
echo $sql;
?>

Prepared Statements से कई Rows Safely Insert करना

untrusted या user-supplied bulk data के लिए, same prepared statement को एक loop के अंदर बार-बार execute करना -- प्रति row एक बार -- हर value को concatenate करने के बजाय safely bound रखता है, prepared statements की safety को कई rows insert करने की क्षमता के साथ combine करते हुए।

उदाहरण: Inserting Multiple Rows Safely with Prepared Statements

php
<?php
// Create a new `SQLite3` instance with ':memory:', stored in `$db`
$db = new SQLite3(':memory:');
$db->exec("CREATE TABLE users (name TEXT)");
// Declare `$stmt`, set to `$db->prepare("INSERT INTO users (name) VALUES (:name)")`
$stmt = $db->prepare("INSERT INTO users (name) VALUES (:name)");
// Loop over `["Sam", "Alex", "Robert'); DROP TABLE users;"]`, binding each item to `$name`
foreach (["Sam", "Alex", "Robert'); DROP TABLE users;"] as $name) {
    $stmt->bindValue(':name', $name, SQLITE3_TEXT);
    $stmt->execute();
}
// Print "All rows inserted safely" to the output
echo "All rows inserted safely";
?>

Performance Compare करना: Multi-Row बनाम Looped Single Inserts

same data के लिए एक single multi-row INSERT statement individual INSERT statements को loop करने से dramatically तेज़ है, क्योंकि इसमें database server तक प्रति row एक की बजाय सिर्फ एक network round-trip शामिल है -- यह अंतर सैकड़ों या हज़ारों rows insert करते समय बहुत noticeable हो जाता है।

उदाहरण: Comparing Performance: Multi-Row vs Looped Single Inserts

php
<?php
$db = new SQLite3(':memory:');
$db->exec("CREATE TABLE users (name TEXT)");
$start = microtime(true);
$db->exec("INSERT INTO users (name) VALUES ('A'), ('B'), ('C')"); // one round-trip
echo "Multi-row insert: " . round(microtime(true) - $start, 5) . "s";
?>

बहुत बड़े Inserts को Batch करना

बहुत बड़े datasets (दसियों हज़ार rows या ज़्यादा) के लिए, सब कुछ एक giant multi-row statement में insert करना MySQL के configured packet size limit से टकरा सकता है -- data को reasonably sized batches में split करना (जैसे प्रति statement 500 या 1000 rows) speed को उस limit के against balance करता है।

उदाहरण: Batching Very Large Inserts

php
<?php
// Declare `$rows`, set to `range(1, 1500)`
$rows = range(1, 1500);
// Declare `$batches`, set to `array_chunk($rows, 500)`
$batches = array_chunk($rows, 500);
// Print `count($batches) . " batches of up to 500 rows each"` to the output
echo count($batches) . " batches of up to 500 rows each";
?>
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
आम गलतियां
  1. हर row के लिए loop करके एक अलग mysqli_query() call चलाना जब एक single multi-row INSERT कहीं ज़्यादा तेज़ होगा और database connection पर कहीं कम load डालेगा।
  2. raw, un-escaped values को SQL string में concatenate करके एक multi-row INSERT बनाना, single-row insert जैसे ही SQL injection का दरवाज़ा खोलते हुए।
  3. यह भूल जाना कि अगर bulk INSERT में कोई एक row किसी constraint को violate करे, storage engine और settings के आधार पर पूरा statement fail हो सकता है, potentially सारी rows reject करते हुए।
चैप्टर सारांश
  • INSERT INTO table (col1, col2) VALUES (a, b), (c, d), (e, f) एक single statement में तीन rows insert करता है।
  • Multi-row inserts single-row inserts को loop करने से काफी तेज़ हैं, क्योंकि उनमें database server तक कहीं कम round trips शामिल होती हैं।
  • Prepared statements अभी भी multi-row inserts के लिए इस्तेमाल किए जा सकते हैं same prepared statement को अलग bound values के साथ बार-बार execute करके।

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.