要在數(shù)據(jù)庫(kù)中查看記錄,首先,我們需要使用TableRegistry類獲得一個(gè)表(table)??梢杂肨ableRegistry類的get()方法獲取表的實(shí)例。get()方法將表名作為參數(shù)。
現(xiàn)在,使用這個(gè)實(shí)例的find()方法從數(shù)據(jù)庫(kù)中查找記錄。該方法將從所請(qǐng)求的表中返回所有記錄。
修改config / routes.php文件文件如下。
config/routes.php文件
<?php use CakeCorePlugin; use CakeRoutingRouteBuilder; use CakeRoutingRouter; Router::defaultRouteClass('DashedRoute'); Router::scope('/', function (RouteBuilder $routes) { $routes->connect('/users', ['controller' => 'Users', 'action' => 'index']); $routes->fallbacks('DashedRoute'); }); Plugin::routes();
在src/Controller/下創(chuàng)建一個(gè)UsersController.php文件。復(fù)制以下代碼至其中。
src/Controller/UsersController.php
<?php namespace AppController; use AppControllerAppController; use CakeORMTableRegistry; use CakeDatasourceConnectionManager; class UsersController extends AppController{ public function index(){ $users = TableRegistry::get('users'); $query = $users->find(); $this->set('results',$query); } } ?>
在src/Template目錄下創(chuàng)建一個(gè)Users目錄 ,如果已創(chuàng)建則忽略,在該Users目錄下創(chuàng)建一個(gè)名為index.ctp的視圖文件。復(fù)制以下代碼至其中。
src/Template/Users/index.ctp
<a href = "add">Add User</a> <table> <tr> <td>ID</td> <td>Username</td> <td>Password</td> <td>Edit</td> <td>Delete</td> </tr> <?php foreach ($results as $row): echo "<tr><td>".$row->id."</td>"; echo "<td>".$row->username."</td>"; echo "<td>".$row->password."</td>"; echo "<td><a href = '".$this->Url->build (["controller" => "Users","action"=>"edit",$row->id])."'>Edit</a></td>"; echo "<td><a href = '".$this->Url->build (["controller" => "Users","action"=> "delete",$row->id])."'>Delete</a></td></tr>"; endforeach; ?> </table>
通過訪問以下網(wǎng)址執(zhí)行上面的例子。
http://localhost:85/CakePHP/users
執(zhí)行以上程序,您會(huì)看到如下頁(yè)面。
更多建議: