CodeIgniter SELECT Database record
To fetch all data from database, one more page in Model folder of CodeIgniter will be created. There will be some changes in controller's and view's files also.
Controller file (Baby_form.php) is shown below.
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Baby_form extends CI_Controller {
public function __construct()
{
parent::__construct();
//calling model
$this->load->model("Babymodel", "a");
}
public function index()
{
$this->load->view("baby_form_select");
}
function savingdata()
{
//this array is used to get fetch data from the view page.
$data = array(
'name' => $this->input->post('name'),
'meaning' => $this->input->post('meaning'),
'gender' => $this->input->post('gender'),
'religion' => $this->input->post('religion')
);
//insert data into database table.
$this->db->insert('baby',$data);
redirect("baby_form/index");
}
}
?>
We have added a constructor to load the model page. Highlighted code is added to fetch the inserted record. And our view page is now baby_form_select.php
View file (baby_form_select.php) is shown below.
<!DOCTYPE html>
<html>
<head>
<title>Baby Form Add</title>
</head>
<body>
<form method="post" action="<?php echo site_url('baby_form/savingdata'); ?>">
<table>
<tr>
<td>Name:</td>
<td>:</td>
<td><input type="text" name="name"></td>
</tr>
<tr>
<td>Meaning:</td>
<td>:</td>
<td><input type="text" name="meaning"></td>
</tr>
<tr>
<td>Gender:</td>
<td>:</td>
<td><input type="text" name="gender"></td>
</tr>
<tr>
<td>Religion:</td>
<td>:</td>
<td><input type="text" name="religion"></td>
</tr><br><br>
<tr>
<input type="submit" name="submit" value="Save">
</tr>
</table>
</form>
<table border="1">
<thead>
<th>ID</th>
<th>NAME</th>
<th>MEANING</th>
<th>GENDER</th>
<th>RELIGION</th>
<th>ACTION</th>
</thead>
<tbody>
<?php
foreach($this->a->fetchtable() as $row)
{
//name has to be same as in the database.
echo "<tr>
<td>$row->id</td>
<td>$row->name</td>
<td>$row->meaning</td>
<td>$row->gender</td>
<td>$row->religion</td>
</tr>";
}
?>
</tbody>
</table>
</body>
</html>
Code in baby_form_select.php file is same as baby_form_add.php. Above codes are added to fetch the record.
Here we have fetched the record in a table with the help of foreach loop. Function fetchtable() is created to fetch the record.
Model file (babymodel.php) is shown below.
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Babymodel extends CI_Model {
function __construct()
{
//call model constructor
parent::__construct();
}
function fetchtable()
{
$query = $this->db->get('baby');
return $query->result();
}
}
?>
In URL, type http://localhost/CodeIgniter/index.php/Baby_form
Look at the above snapshot, all data has been fetched from the table 'baby'.