要在數(shù)據(jù)庫中更新記錄,首先,我們需要使用TableRegistry類獲得一個表(table)??梢杂肨ableRegistry類的get()方法獲取表的實例。get()方法將表名作為參數(shù)?,F(xiàn)在,我們使用這個實例來得到想要更新的記錄。
調(diào)用這個實例的get()方法并傳遞主鍵,查找到會被保存到另一個實例中的記錄。使用這個實例來設置你想要更新的新值,然后調(diào)用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/目錄下創(chuàng)建一個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目錄下創(chuàng)建一個Users目錄 ,如果已創(chuàng)建則忽略,并在該Users目錄下創(chuàng)建一個名為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目錄中創(chuàng)建另一個視圖文件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(); ?>
通過訪問以下網(wǎng)址,然后點擊Edit鏈接來編輯記錄。
http://localhost:85/CakePHP/users
訪問上述網(wǎng)址,并單擊Edit鏈接后,您會看到以下頁面,可也在這里編輯記錄。
更多建議: