search

Home  >  Q&A  >  body text

Best way to batch insert in mysqli?

<p>I'm looking for a SQL injection safe technique to insert a large number of rows (~2000 rows) at once using PHP and MySQLi. </p><p>I have an array that contains all the values ​​it must contain. Currently I'm doing this: </p> <pre class="brush:php;toolbar:false;"><?php $array = array("array", "with", "about", "2000", "values"); foreach ($array as $one) { $query = "INSERT INTO table (link) VALUES (?)"; $stmt = $mysqli->prepare($query); $stmt ->bind_param("s", $one); $stmt->execute(); $stmt->close(); } ?></pre> <p>I tried call_user_func_array() but it resulted in stack overflow. </p> <p>What is a faster way to do this (like inserting them all at once?) but still prevent SQL injection (like prepared statements) and stack overflow? </p>
P粉951914381P粉951914381578 days ago599

reply all(2)I'll reply

  • P粉530519234

    P粉5305192342023-08-25 15:20:13

    Try again, I don't understand why your original code doesn't work after a slight modification:

    $query = "INSERT INTO table (link) VALUES (?)";
    $stmt = $mysqli->prepare($query);
    $stmt->bind_param("s", $one);
    
    foreach ($array as $one) {
        $stmt->execute();
    }
    $stmt->close();

    reply
    0
  • P粉340980243

    P粉3409802432023-08-25 00:31:22

    By putting your inserts into a transaction you should be able to speed things up a lot. You can also move prepare and bind statements outside the loop.

    $array = array("array", "with", "about", "2000", "values");
    $query = "INSERT INTO table (link) VALUES (?)";
    $stmt = $mysqli->prepare($query);
    $stmt ->bind_param("s", $one);
    
    $mysqli->query("START TRANSACTION");
    foreach ($array as $one) {
        $stmt->execute();
    }
    $stmt->close();
    $mysqli->query("COMMIT");

    I tested this code on my web server for 10,000 iterations.

    No transaction: 226 seconds. Transaction time: 2 seconds. Or be two orders of magnitude faster, at least for this test.

    reply
    0
  • Cancelreply