CakePHP学习之三 单表数据显示及增删操作
单表数据显示及增删操作(原文出自http://book.cakephp.org/view/329/Getting-Cake 可以自己看看对比一下,例子还是比较详细的)
1.表取CakePHP学习之二的post表
2. models目录下的post.php
<?php
class Post extends AppModel{
var $name = 'Post';
}
?>
posts_controller.php
<?php
class PostsController extends AppController{
var $name = 'Posts';
//var $scaffold;
function index() {
$this->set('posts', $this->Post->find('all'));
}
function view($id = null) {
$this->Post->id = $id;
$this->set('post', $this->Post->read());
}
function add() {
if (!empty($this->data)) {
if ($this->Post->save($this->data)) {
$this->Session->setFlash('Your post has been saved.');
$this->redirect(array('action' => 'index'));
}
}
}
function delete($id) {
$this->Post->del($id);
$this->Session->setFlash('The post with id: '.$id.' has been deleted.');
$this->redirect(array('action'=>'index'));
}
function edit($id = null) {
$this->Post->id = $id;
if (empty($this->data)) {
$this->data = $this->Post->read();
} else {
if ($this->Post->save($this->data)) {
$this->Session->setFlash('Your post has been updated.');
$this->redirect(array('action' => 'index'));
}
}
}
}
?>
3. views目录下的文件
index.ctp
<?php echo $html->link('Add Post',array('controller' => 'posts', 'action' => 'add'))?>
<h1>Blog posts</h1>
<table>
<tr>
<th>Id</th>
<th>Title</th>
<th>Created</th>
</tr>
<!-- Here is where we loop through our $posts array, printing out post info -->
<?php foreach ($posts as $post): ?>
<tr>
<td><?php echo $post['Post']['id']; ?></td>
<td>
<?php echo $html->link($post['Post']['title'],
"/posts/view/".$post['Post']['id']); ?>
</td>
<td>
<?php echo $html->link('Delete', array('action' => 'delete', 'id' => $post['Post']['id']), null, 'Are you sure?' )?>
<?php echo $html->link('Edit', array('action'=>'edit', 'id'=>$post['Post']['id']));?>
</td>
<td><?php echo $post['Post']['created']; ?></td>
</tr>
<?php endforeach; ?>
</table>
view.ctp
<h1><?php echo $post['Post']['title']?></h1>
<p><small>Created: <?php echo $post['Post']['created']?></small></p>
<p><?php echo $post['Post']['body']?></p>
add.ctp
<h1>Add Post</h1>
<?php
echo $form->create('Post');
echo $form->input('title');
echo $form->input('body', array('rows' => '3'));
echo $form->end('Save Post');
?>
/app/views/posts/edit.ctp <h1>Edit Post</h1> <?php echo $form->create('Post', array('action' => 'edit')); echo $form->input('title'); echo $form->input('body', array('rows' => '3')); echo $form->input('id', array('type'=>'hidden')); echo $form->end('Save Post'); ?>