Fetching data from table using MVC way with CodeIgniter in PHP
<?php
defined("BASEPATH") or exit("No direct script access allowed");
class Contacts extends CI_Controller
{
public function index()
{
$this->load->model("ContactsModel");
$data["records"] = $this->ContactsModel->getContacts();
$this->load->view("contacts_view", $data);
}
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Contacts View list</title>
</head>
<body>
<h1>Contacts View list</h1>
<?php
if (count($records) > 0) {
?>
<table border="1">
<tr>
<th>Id</th>
<th>First_Name</th>
<th>Last_Name</th>
<th>Age</th>
</tr>
<?php
foreach ($records as $rec) {
?>
<tr>
<td><?php echo $rec->id; ?></td>
<td><?php echo $rec->first_name; ?></td>
<td><?php echo $rec->last_name; ?></td>
<td><?php echo $rec->age; ?></td>
</tr>
<?php
}
?>
</table>
<?php
} else {
echo "Sorry! No Records Found<br>";
}
?>
</body>
</html>
<?php
defined("BASEPATH") or exit("No direct script access allowed");
class ContactsModel extends CI_Model
{
public function getContacts()
{
$this->load->database();
$result = $this->db->query("SELECT * FROM students");
if ($result->num_rows() > 0) {
return $result->result();
} else {
return false;
}
}
}


Comments
Post a Comment