CakePHP-查看记录



要查看数据库记录,我们首先需要使用TableRegistry类来获取表。我们可以使用get()方法从注册表中获取实例。 get()方法将数据库表的名称作为参数。

现在,该新实例用于使用find()方法从数据库中查找记录。此方法将返回请求表中的所有记录。

如以下代码所示,在config / routes.php文件中进行更改。

config / routes.php

<?php use Cake\Http\Middleware\CsrfProtectionMiddleware;
use Cake\Routing\Route\DashedRoute;
use Cake\Routing\RouteBuilder;
$routes-?>setRouteClass(DashedRoute::class);
$routes->scope('/', function (RouteBuilder $builder) {
   $builder->registerMiddleware('csrf', new CsrfProtectionMiddleware([
      'httpOnly' => true,
   ]));
   $builder->applyMiddleware('csrf');
   //$builder->connect('/pages',['controller'=>'Pages','action'=>'display', 'home']);
   $builder->connect('/users', ['controller' => 'Users', 'action' => 'index']);
   $builder->fallbacks();
});

src / Controller / UsersController.php中创建一个UsersController.php文件将以下代码复制到控制器文件中。

src / controller / UsersController.php

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

src / Template上创建目录Users 如果已经创建,则忽略它,并在该目录下创建一个名为index.phpView文件将以下代码复制到该文件中。

src /模板/用户/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>";
      echo "</td><td>".$row->password."</td>";
      echo "<td><a href="%22.%24this-<Url->build(%5B%22controller%22%20=>%20%22Users%22,%22action%22%20=>%20%22edit%22,%24row->id%5D).%22">Edit</a></td>";
      echo "<td><a href="%22.%24this->Url->build(%5B%22controller%22%20=>%20%22Users%22,%22action%22%20=>%20%22delete%22,%24row->id%5D).%22">Delete</a></td>";
      endforeach;
   ?>
</table>

通过访问以下URL http:// localhost / cakephp4 / users执行上面的示例

输出

执行后,上述URL将为您提供以下输出。

执行时

Made with ❤️ in Chengdu. Copyright reserved 2019-2022.

蜀ICP备20006366号-1