insert multiple rows via a php array into mysql

后端 未结 12 1528
自闭症患者
自闭症患者 2020-11-21 22:35

I\'m passing a large dataset into a MySQL table via PHP using insert commands and I\'m wondering if its possible to insert approximately 1000 rows at a time via a query othe

12条回答
  •  攒了一身酷
    2020-11-21 23:18

    Assembling one INSERT statement with multiple rows is much faster in MySQL than one INSERT statement per row.

    That said, it sounds like you might be running into string-handling problems in PHP, which is really an algorithm problem, not a language one. Basically, when working with large strings, you want to minimize unnecessary copying. Primarily, this means you want to avoid concatenation. The fastest and most memory efficient way to build a large string, such as for inserting hundreds of rows at one, is to take advantage of the implode() function and array assignment.

    $sql = array(); 
    foreach( $data as $row ) {
        $sql[] = '("'.mysql_real_escape_string($row['text']).'", '.$row['category_id'].')';
    }
    mysql_query('INSERT INTO table (text, category) VALUES '.implode(',', $sql));
    

    The advantage of this approach is that you don't copy and re-copy the SQL statement you've so far assembled with each concatenation; instead, PHP does this once in the implode() statement. This is a big win.

    If you have lots of columns to put together, and one or more are very long, you could also build an inner loop to do the same thing and use implode() to assign the values clause to the outer array.

提交回复
热议问题