The easiest way to display data from database in CakePHP 2

In this tutorial I'm going to explain to you how you can display data from database in CakePHP 2. I will speak step by step how to extract all information from a table in your database.

I have created a new table in my database, called Articles. Now I will create a new Controller called ArticlesController(called as my created table.).

In my Controller I will add action index with this code:

public function index() {
$this->set('articles', $this->Article->find('all'));
}

Now, I will create a new model, called Post with this code:

class Article extends AppModel {
}

In my routes I will add new route:

Router::connect('/articles/', array('controller' => 'articles', 'action' => 'index', 'article'));

In my View folder I will create a new folder, called Posts with index.cpt file. And in the index.cpt file I will add this code:

This code will display the data from my database. I have two fields in my database: id and title. You can add other fields and display data with

Video tutorial:

If you have this error: "Table Articles for model Article was not found in datasource default."

You must edit the name of your table. It must be like the name of your model and controller.

If you have this error: "Call to a member function find() on a non-object"

You must edit the name of your Controller. It must be called like the name of your model(with Controller at the end).









Leave a Comment