CakePHP的更新记录
要在数据库中更新记录,首先,我们需要使用TableRegistry类获得一个表(table)。可以用TableRegistry类的get()方法获取表的实例。get()方法将表名作为参数。现在,我们使用这个实例来得到想要更新的记录。
调用这个实例的get()方法并传递主键,查找到会被保存到另一个实例中的记录。使用这个实例来设置你想要更新的新值,然后调用TableRegistry类的实例(这个实例)的save()方法来更新记录。
例
修改config/routes.php文件如下。
config/routes.php文件
<?php use CakeCorePlugin; use CakeRoutingRouteBuilder; use CakeRoutingRouter; Router::defaultRouteClass('DashedRoute'); Router::scope('/', function (RouteBuilder $routes) { $routes->connect('/users/edit', ['controller' => 'Users', 'action' => 'edit']); $routes->fallbacks('DashedRoute'); }); Plugin::routes();
在src/Controller/目录下创建一个UsersController.php文件。复制以下代码至其中。
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); } public function edit($id){ if($this->request->is('post')){ $username = $this->request->data('username'); $password = $this->request->data('password'); $users_table = TableRegistry::get('users'); $users = $users_table->get($id); $users->username = $username; $users->password = $password; if($users_table->save($users)) echo "User is udpated"; $this->setAction('index'); } else { $users_table = TableRegistry::get('users')->find(); $users = $users_table->where(['id'=>$id])->first(); $this->set('username',$users->username); $this->set('password',$users->password); $this->set('id',$id); } } } ?>
在src/Template目录下创建一个Users目录 ,如果已创建则忽略,并在该Users目录下创建一个名为index.ctp的视图文件。复制以下代码至其中。
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>
在Users目录中创建另一个视图文件edit.ctp,复制以下代码至其中。
src/Template/Users/edit.ctp
<?php echo $this->Form->create("Users",array('url'=>'/users/edit/'.$id)); echo $this->Form->input('username',['value'=>$username]); echo $this->Form->input('password',['value'=>$password]); echo $this->Form->button('Submit'); echo $this->Form->end(); ?>
通过访问以下网址,然后点击Edit链接来编辑记录。
http://localhost:85/CakePHP/users
输出
访问上述网址,并单击Edit链接后,您会看到以下页面,可也在这里编辑记录。