Home >>Codeigniter Tutorial >How to 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.
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.
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])); } ?>
<div class="box-body table-responsive" >
<table id="example1" class="table table-bordered table-striped">
<thead>
<tr>
<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>
</tr>
</thead>
<form method="post">
<?php for ($i=0; $i <3 ; $i++)
{?>
<tr>
<td><input type="text" name="Name[]"></td>
<td><input type="text" name="Depmt[]"></td>
<td><input type="text" name="course[]"></td>
</tr>
<?php } ?>
<tr><td colspan="3" align="center">
<input type="submit" class="btn btn-primary" value="save"></td></tr>
</form>
</table>
</div>
</div>
</div>
</body>
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Dashboard extends CI_Controller
{
function __construct()
{
parent::__construct();
$this->load->model('AdminModel');
//$this->load->helper('url');
}
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)
{
$this->load->view('admin/center_emp_details');
}
else
{
$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],);
$this->db->insert('salary',$data);
}
}
}
}
?>