Categories
CodeIgniter

How to retrieve data from database in CodeIgniter?

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.

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

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

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

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

By Arjun

I am Arjun from Hyderabad (India). I have been working as a software engineer from the last 7+ years, and it is my passion to learn new things and implement them as a practice. Aside from work, I like gardening and spending time with pets.

45 replies on “How to retrieve data from database in CodeIgniter?”

Dear sir, there is a small mistake on the posts_view.php.

Basically instead of “foreach($posts as $post) ” the correct variable in this case would be “foreach($query as $post) ” because the data is stored in the variable called “query”.

Other than that this tutorial is spot on.

could you please help me i am still getting an error.

Message: Undefined variable: query

*****my view file: *********

Display Records From Database Using Codeigniter

Post Id

Post Title

Title;?>

time;?>

******my controller *******

public function index() {

$this->load->model(‘users_model’); // load model

$this->data[‘posts’] = $this->users_model->getPosts();

$this->load->view(‘manage_news’, $this->data);

}

*****my model ********

function getPosts(){

$this->db->select(“Title,time”);

$this->db->from(‘news’);

$query = $this->db->get();

return $query->result();

}

A PHP Error was encountered

Severity: Notice

Message: Undefined variable: posts

Filename: views/viewad.php

Line Number: 17

A PHP Error was encountered

Severity: Warning

Message: Invalid argument supplied for foreach()

Filename: views/viewad.php

Line Number: 17

//controller

load->database();

//load the model

$this->load->model(‘vehicles’);

//load the method of model

$data[‘results’]=$this->vehicles->select();

//return the data in view

$this->load->view(‘template/header’);

$this->load->view(‘view_ad’, $data);

$this->load->view(‘template/footer’);

}

}

?>

//model

db->select(”name”);

$this->db->from(‘vehicles’);

$query = $this->db->get();

return $query->result();

}

}

?>

//view

name; ?>

I also have the same problem:

A PHP Error was encountered
Severity: Notice
Message: Undefined variable: posts
Filename: views/menu_page.php
Line Number: 24

I tried changing the variable to $query but that didn’t help either.

Does someone maybe have a solution for this?

CONTROLLER:
public function index() {

$this->data[‘posts’] = $this->menu_database->get_menu();

$this->load->view(‘menu_page’, $this->data);
}

MODEL:

function get_menu(){

$this->db->select(“gerechtnaam, gerechttype, gerechtprijs”);

$this->db->from(‘tbl_menu’);

$posts = $this->db->get();

return $posts->result();
}

VIEW:

gerechtnaam; echo $post->gerechttype; echo $post->gerechtprijs;?>

Thanks in advance, would be a real help

In your modal you are returning multiple rows, so you should apply iterators on $posts.

EX:

foreach($posts as $post) { ?>

gerechtnaam; echo $post->gerechttype; echo $post->gerechtprijs;?>

<?php }

Thank you for your reply but the foreach is already in my code. Sorry, i forgot to copy that part of the code. Still got that error though, but thanks anyway great tutorial

could you please help me i am still getting an error.

Message: Undefined variable: query

*****my view file: *********

Display Records From Database Using Codeigniter

Post Id

Post Title

Title;?>

time;?>

******my controller *******

public function index() {

$this->load->model(‘users_model’); // load model

$this->data[‘posts’] = $this->users_model->getPosts();

$this->load->view(‘manage_news’, $this->data);

}

*****my model ********

function getPosts(){

$this->db->select(“Title,time”);

$this->db->from(‘news’);

$query = $this->db->get();

return $query->result();

}

still not working 🙁

error: Message: Undefined variable: posts

Post Id
Post Title

php foreach($posts as $post){

Title;?>
time;?>

thanks for all your help so far.
it is still giving an error: Message: Undefined variable: posts

but also displaying -> no posts !

but i have data in the database and it is all connected properly.

i am still getting an error-> unidentified variable posts. but its also displaying no posts” please help!!!
table>

Post Id

Post Title

0) {

foreach($posts as $post) { ?>

title; ?>

I was having the same problem as most of you here, on the “$posts as $post” line, $posts was being called as undefined and the page wasn’t working. Go to your controller and where it says:

$this->data[‘posts’] = $this->PostModel->getPosts(); // calling Post model method getPosts()

remove the FIRST $this you see. then try again. so it should be:

data[‘posts’] = $this->PostModel->getPosts(); // calling Post model method getPosts()

that fixed mine! hope this helps

sir plz help me error object not found!

……controller…….

load->database(); // load database
$this->load->model(‘userModel’); // load model
}

public function index() {

$this->data[‘users’] = $this->userModel->getusers(); // calling Post model method getusers()
die($this->data[‘users’]);

$this->load->view(‘users_view’, $this->data); // load the view file , we are passing $data array to view file
}

}
?>

………..model………

db->select(“user_id,user_name,”);
$this->db->from(‘users_tbl’);
$query = $this->db->get();
return $query->result();
}

}
?>

……………………..view…………………

Users List

User Id
User name

users_id;?>
users_name;?>

……………………url………………………

http://localhost/abc/user

http://localhost/abc/user/index try both

An uncaught Exception was encountered

Type: RuntimeException

Message: Unable to locate the model you have specified: Rtt

Filename: C:xampphtdocsstyliorsystemcoreLoader.php

Line Number: 344

Backtrace:

File: C:xampphtdocsstyliorapplicationcontrollersControler1.php

Line: 9

Function: model

File: C:xampphtdocsstyliorindex.php

Line: 292

Function: require_once

when iam running in my localsystem this error showing sir can u please help me

i had use this code its working fine. but the problem is when i try to fetch data from database in codeigniter then it fetch the data but pick only one word and ignore the remaining data means after space.
i am using ci-3.0.6 version.

Whenever i am trying to pass the data from the controller to view page i am getting error as below

A PHP Error was encountered

Severity: Notice

Message: Undefined variable: datalist

Filename: views/display_registration.php

Line Number: 82
Backtrace:
File: D:wampwwwcitestnewapplicationviewsdisplay_registration.php

Line: 82

Function: _error_handler

File: D:wampwwwcitestnewapplicationcontrollersMysite.php

Line: 158

Function: view

File: D:wampwwwcitestnewindex.php

Line: 292

Function: require_once

A PHP Error was encountered

Severity: Warning

Message: Invalid argument supplied for foreach()

Filename: views/display_registration.php

Line Number: 82
Backtrace:
File: D:wampwwwcitestnewapplicationviewsdisplay_registration.php

Line: 82

Function: _error_handler

File: D:wampwwwcitestnewapplicationcontrollersMysite.php

Line: 158

Function: view

File: D:wampwwwcitestnewindex.php

Line: 292

Function: require_once

I am getting the above ERROR, i am not able to display the table content to the view page

MY CODE AS FOLLOWS:
CONTROLLER:
load->model(‘login’);
$data[‘datalist’] = $this->login->viewData();
$this->load->view(‘display_registration’,$data);

}

}

MODEL:

db->query(“select * from register where rstatus = 1”);
return $query->result_array();

}

}

VIEW : display_registration.php

Employee Registration View

Date of Joining
Employee Name
Designation
Company
Address
Options

<a href="”>Edit <a href="”>Delete

Please help me Arjun. Thanks in advance

Greetings Arjun, I’m also running into the same issue that many others are. In my code the data is stored in a variable called $foo2.

In my view I am not able to access my data via $foo2 as anticipated, however I am able to access it via $this->data[‘foo2’];

Looking at the remainder of the code base (I’m retrofitting this into some existing code) the only other discernible difference that I can see from your sample is that in my controller my class is defned by

class Login extends MY_Controller

rather than

class Foo2 extends CI_Controller (my version of what you have in your sample)

This is because, again, I’m integrating it into existing code.

Any suggestions? I can of course proceed with $this->data[‘foo2’]; as a stopgap if needed…

this is my firstname with PHP-Codeigniter! I just copy and paste your code just to make a try! and this is what happens

Fatal error: Uncaught Error: Call to undefined function mysql_pconnect() in C:xampphtdocstrysystemdatabasedriversmysqlmysql_driver.php:92 Stack trace: #0 C:xampphtdocstrysystemdatabaseDB_driver.php(116): CI_DB_mysql_driver->db_pconnect() #1 C:xampphtdocstrysystemdatabaseDB.php(149): CI_DB_driver->initialize() #2 C:xampphtdocstrysystemcoreLoader.php(347): DB(Array, NULL) #3 C:xampphtdocstryapplicationcontrollersPost.php(6): CI_Loader->database() #4 C:xampphtdocstrysystemcoreCodeIgniter.php(309): Post->__Construct() #5 C:xampphtdocstryindex.php(202): require_once(‘C:\xampp\htdocs…’) #6 {main} thrown in C:xampphtdocstrysystemdatabasedriversmysqlmysql_driver.php on line 92

what will do to this???? I manipulated this one and its always ending up errors, makes errors,

Dear posts is the array which is coming from controller…
$this->data[‘posts’]
you can see the syntax in controller.. while post is key values pair which you can create by yourn choice name.. like

foreach($posts as $p) or foreach($posts as $something) etc.. means the $posts is same as in controller array.

hey do i get the db data in the respective field after fetching ?? for example as per your code, u have fetched id,title and content, can i get these data in my view page in respective fields like id, title and content after executing getposts()

Leave a Reply

Your email address will not be published. Required fields are marked *