Skip to content

How to retrieve data from database in CodeIgniter?

Last updated on February 1, 2018

In this CodeIgniter tutorial, I will show you how to fetch data from database using model, view, controller approach.

As usual, we need need to setup database connection in order to perform actions like select, insert, delete, update..etc in the database. open your database.php file and set up the database configuration values, after setting up the database connection, As we know, CodeIgniter use MVC pattern. We will use Model to retrieve data from the database.

open your application/database.php, set your database credentials.

$db['default']['hostname'] = "localhost"; // database host
$db['default']['username'] = "root"; // db user name
$db['default']['password'] = ""; // db user password 
$db['default']['database'] = "arjunphp_demo"; // database name 

Then create a controller called Post.php in you application/controller/ directory.

load->database(); // load database
   $this->load->model('PostModel'); // load model 
 }

 public function index() {
   $this->data['posts'] = $this->PostModel->getPosts(); // calling Post model method getPosts()
   $this->load->view('posts_view', $this->data); // load the view file , we are passing $data array to view file
 }


}
?>

Now create you model file called PostModel.php in our Application/Models/ directory.Which will query the database table and fetch the records.

db->select("post_id,post_title,post_content"); 
  $this->db->from('post_tbl');
  $query = $this->db->get();
  return $query->result();
 }

}
?>

the final step lets create posts_view.php file under folder name application/views. Here we are going to display the posts information.



  
  
  
   

    

Display Records From Database Using Codeigniter

Post Id Post Title
post_id;?> post_title;?>

Now point your browser to http://localhost/post/ you will get the result.

0 0 votes
Article Rating
Subscribe
Notify of
guest

45 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments