Home >>Codeigniter Tutorial >How to insert multiple rows in MySQL using Codeigniter

How to insert multiple rows in MySQL using Codeigniter

Insert multiple rows in mysql using codeigniter

In this article, we will discuss How to save Single and Multiple records from the MySQL database using the CodeIgniter framework. if you want to enter one data on a website then we can use the Insert Query Input method method and if you want to add multiple records to the database we will be able to use the insert_batch Query Method.

Multiple Records Update

In this step, we will add multiple rows values to CodeIgniter. So we will use the insert_batch Query method for the example below, You can see the following example below.

Insert multiple rows in mysql using codeigniter Core Fuction

Ex1(using default array value)

<?php $Mydata = array( array( 'name' => 'Your Name' , 'email' => 'Your Email' , 'course' => 'Your Course' ), array( 'name' => 'Your Name' , 'email' => 'Your Email' , 'course' => 'Your Course' ) ); $this->db->insert_batch('mytable', $Mydata); //OR $post = $this->input->post(); for ($i = 0; $i < count($post['name']; $i++) { $this->db->insert('my_table', array('name' => $post['name'][$i], 'email' => $post['email'][$i], 'course' => $post['course'][$i])); } ?>

Examp2 Using Controller & View form templates


<div class="box-body table-responsive" >
    <table id="example1" class="table table-bordered table-striped">
      <th class="col-md-2 col-xs-5">Name</th>
      <th class="col-md-2 col-xs-3">Depmt</th>
      <th class="col-md-2 col-xs-3">course</th>
    <form method="post">
      <?php for ($i=0; $i <3 ; $i++) 
      <td><input type="text" name="Name[]"></td>
      <td><input type="text" name="Depmt[]"></td>
      <td><input type="text" name="course[]"></td>
    <?php  } ?>
<tr><td colspan="3" align="center"> 
  <input type="submit" class="btn btn-primary" value="save"></td></tr>


defined('BASEPATH') OR exit('No direct script access allowed');
class Dashboard extends CI_Controller 
   function __construct()
public function center_details()

		$this->form_validation->set_rules('Name[]', 'Name', 'required');
		$this->form_validation->set_rules('Depmt[]', 'department', 'required');
		$this->form_validation->set_rules('course[]', 'Course', 'required');

			if ($this->form_validation->run() == FALSE)
				$post = $this->input->post();
				for ($i = 0; $i < count($post['Name']); $i++) 
				$data=array('name' => $post['Name'][$i],
							'department' => $post['Depmt'][$i],
							'course' => $post['course'][$i],);


Multiple Records Update Result