How to insert multiple rows from array using CodeIgniter framework? |
To insert multiple rows from an array using the CodeIgniter framework, you can utilize the insert_batch() function provided by the CI_DB class. This function efficiently handles bulk data insertion, enabling you to seamlessly add multiple records to your database. Here's a step-by-step guide on how to implement this method:
1. Prepare the Data Array: Construct an array that stores the data for each row you intend to insert into the database. Each element of the array should represent a single row, with the keys corresponding to the column names in your table. For instance, if your table has columns named id, name, and email, your data array might look like this: PHP $data = [ ['id' => 1, 'name' => 'John Doe', 'email' => '[email protected]'], ['id' => 2, 'name' => 'Jane Doe', 'email' => '[email protected]'], // ... Additional rows ]; Use code with caution. Learn more 2. Load the Database Class: To access the database functionality, you need to load the database class within your controller or model file. Use the following code to load the database instance: PHP $this->load->database(); Use code with caution. 3. Insert Multiple Rows Using insert_batch(): Once the data array and database instance are ready, you can utilize the insert_batch() function to insert multiple rows simultaneously. The function takes two arguments: the table name and the data array. PHP $this->db->insert_batch('users', $data); Use code with caution. This code will insert all the rows from the $data array into the users table. The insert_batch() function will return an integer indicating the number of rows successfully inserted. |
Messages In This Thread |
How to insert multiple rows from array using CodeIgniter framework? - by JiwanFilembar - 10-10-2022, 03:45 AM
RE: How to insert multiple rows from array using CodeIgniter framework? - by superior - 10-10-2022, 11:48 PM
RE: How to insert multiple rows from array using CodeIgniter framework? - by Sprint - 11-22-2022, 04:35 AM
RE: How to insert multiple rows from array using CodeIgniter framework? - by superior - 11-23-2022, 01:05 AM
RE: How to insert multiple rows from array using CodeIgniter framework? - by jackbob - 11-24-2023, 07:16 AM
|