cakephp对数据库的增删改查
為什么80%的碼農都做不了架構師?>>> ??
拿一個對于posts的數據庫的舉例好了:
主頁如下:
<?php
?echo 'this is index:';
?foreach($posts as $post){
??echo "id:".$post['Post']['id']."|";
??/*點擊title的時候會傳遞出post的id*/
?? echo $this->Html->link($post['Post']['title'],
??array('controller' => 'posts', 'action' => 'view',$post['Post']['id']))."||";
??/*點擊Edit的時候會傳送id*/
??echo $this->Html->link("Edit",
??array('controller' => 'posts', 'action' => 'goto_edit',$post['Post']['id']))."||";
??/*點擊delete的時候會傳送該Post的id*/
??echo $this->Html->link('delete',
??array('controller' => 'posts', 'action' => 'delete', $post['Post']['id']));
??
??echo "<br>";
??
?}
?>
/*創建一個新的Post,經試驗表明form的名字貌似是隨意取的,關鍵是里面的input的數據的名字,起的和數據庫里的字段一樣即可*/
<form name="Post" action="/lab/posts/add/" method='post'>
<input type="text" name="title"/>
<input type="submit" value="submit"/>
</form>
//
? 接下來是controller:
<?php
??? class PostsController extends AppController{
??????? /*總入口的方法*/
??????? public function index(){
??????????? $result = $this->Post->find("all");
??????????? $this->set('posts',$result);
??????? }
??????? /*刪除的方法,把id放入到參數中,目測應該算是類似于get的方法*/
??????? public function delete($id){
??????????? $this->Post->delete($id);
??????????? $this->render('delete');
??????? }
??????? /*添加一個post的方法,由于我的表中有id自增的設置,所以沒有添加id*/
??????? public function add(){
??????????? if(!empty($this->data)){
??????????????? $this->Post->create();
??????????????? $this->Post->save($this->data);
?????????????? // if(!);
??????????????? $this->render('add');
??????????? }
??????? }
??????? /*這個應該算是查,詳細的看一篇post的信息*/
??????? public function view($id){
??????????? $this->set('id',$id);
??????????? $result = $this->Post->findById($id);
??????????? $this->set('title',$result['Post']['title']);
??????????? //print_r($result);
??????? }
??????? /*這個我設置為編輯的緩沖,點擊編輯后,進入到編輯頁面(中間頁面),此時需要傳遞一個id即可*/
??????? public function goto_edit($id){
??????????? $this->set('id',$id);
??????????? $this->render("goto_edit");
??????? }
??????? /*編輯的方法,不過貌似怎么和創建是一樣的*/
??????? public function edit(){
??????????? echo "this is id:".$this->data['id'];
??????????? if(empty($this->data)){
??????????????? $this->data = $this->Post->read(null,$id);
??????????? }else{
??????????????? $this->Post->create();
??????????????? $this->Post->save($this->data);
??????????? }
??????????? $this->render("edit");
??????? }
??? }
?>
/
我的數據庫是這樣的,總共就兩個字段,沒什么特別的:
+-------+-------------+------+-----+---------+----------------+| Field | Type??????? | Null | Key | Default | Extra????????? |
+-------+-------------+------+-----+---------+----------------+
| title | varchar(50) | YES? |???? | NULL??? |??????????????? |
| id??? | int(11)???? | NO?? | PRI | NULL??? | auto_increment |
+-------+-------------+------+-----+---------+----------------+
?
轉載于:https://my.oschina.net/MrHou/blog/156454
總結
以上是生活随笔為你收集整理的cakephp对数据库的增删改查的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 由单例模式学到:静态构造函数和静态字段
- 下一篇: QL Server 中四种匹配符的含义