How to loop insert data to database in codeigniter?

Member

by lily , in category: PHP Frameworks , a year ago

How to loop insert data to database in codeigniter?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by herminia_bruen , a year ago

@lily 

To loop insert data to a database in CodeIgniter, you can follow these steps:

  1. Create a model function to insert data into the database. Here is an example model function that inserts data into a table called items_table:
1
2
3
public function insert_data($data) {
    $this->db->insert('items_table', $data);
}


  1. In your controller, retrieve the data that you want to insert into the database and loop through it. Here is an example of how you can do that:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
public function insert_multiple_data() {
    $data = array(
        array('name' => 'Item 1', 'price' => 10),
        array('name' => 'Item 2', 'price' => 20),
        array('name' => 'Item 3', 'price' => 30)
    );

    foreach($data as $item) {
        $this->your_model->insert_data($item);
    }

    echo "Data inserted successfully!";
}


  1. Finally, create a route in your routes.php file to access the insert_multiple_data() function in your controller:
1
$route['insert-multiple-data'] = 'Your_Controller/insert_multiple_data';


Now, when you visit the URL corresponding to the route you defined, the data will be looped and inserted into the database.

Related Threads:

How to insert json data into mysql database?
How to insert .txt file data into database using php?
How to insert .txt file data into database using php?
How to insert data directly from excel to oracle database?
How to use for loop for insert in oracle?
How to insert multiple record without loop in laravel?