Performing Bulk Row Insertion with CodeIgniter
Problem
To avoid creating extremely long queries with potentially thousands of appended values, it's advisable to explore methods for inserting multiple MySQL rows simultaneously using a single query.
Solution
Inserting multiple rows in MySQL is far more efficient than performing individual insertions. To optimize this process with CodeIgniter, take advantage of the implode() function.
Implementation
Start by creating an array to hold your SQL statements:
$sql = array();
Next, iterate through your dataset and build the SQL statements:
foreach( $data as $row ) { $sql[] = '("'.mysql_real_escape_string($row['text']).'", '.$row['category_id'].')'; }
Finally, execute the query using implode():
mysql_query('INSERT INTO table (text, category) VALUES '.implode(',', $sql));
Advantages
This approach minimizes copying by assembling the SQL statement in parts and using implode() to concatenate them efficiently. For datasets with many columns and potentially lengthy values, consider using a nested loop to dynamically build the SQL statements.
The above is the detailed content of How Can I Efficiently Perform Bulk Row Insertion in CodeIgniter?. For more information, please follow other related articles on the PHP Chinese website!