.


Divya


Retrieve data from database using CakePHP framework


In this example we will discuss about how to retrieve a record or data from MySQL database using CakePHP framework PHP.

For retrieve data from MySQL database using CakePHP framework first we have to create a table in data base.

After create a table in the MySQL database you need to insert record or data on it.If you want to know how to insert data in CakePHP framework please visit the link : Insert data in CakePHP.

The SELECT statement is used to retrieve data from one or more tables:

The SQL query for retrieve specific column.

SELECT column_name(s) FROM table_name

or we can use the * character to retrieve ALL columns from a table:

SELECT * FROM table_name

To learn more about SQL, please visit our SQL tutorial.


We use 3 file for retrieve students data.

  1. routes.php
  2. UsersController.php
  3. index.ctp

config/routes.php

<?php
Router::defaultRouteClass('DashedRoute');
Router::scope('/', function (RouteBuilder $routes) {
$routes->connect('/users', ['controller' => 'Users', 'action' => 'index']);
$routes->fallbacks('DashedRoute');
});
Plugin::routes();

src/controller/UsersController.php

<?php
namespace App\Controller;
use App\Controller\AppController;
use Cake\ORM\TableRegistry;
use Cake\Datasource\ConnectionManager;
use Cake\Auth\DefaultPasswordHasher;
class UsersController extends AppController{
public function index(){
$users = TableRegistry::get('users');
$query = $users->find();
$this->set('results',$query);
}
}

src/Template/Users/index.ctp

<!DOCTYPEhtml>
<html>
<body>
<table>
<tr>
<td>ID</td>
<td>First Name</td>
<td>Last Name</td>
<td>City</td>
<td>Email</td>
</tr>
<?php
foreach ($results as $row):
echo "<tr><td>".$row->id."</td>";
echo "<td>".$row->first_name."</td>";
echo "<td>".$row->last_name."</td>";
echo "<td>".$row->city."</td>";
echo "<td>".$row->email."</td>";
endforeach;
?>
</table>
</body>
</html>
Id first name last name City name Email Id
1 Divyasundar Sahu Mumbai divyasundar@gmail.com
2 Hritika Sahu Pune hritika@gmail.com
3 Milan Jena Chennai milanjena@gmail.com


.