【发布时间】:2015-04-20 03:36:49
【问题描述】:
我正在尝试使用 codeigniter 向数据库中插入一行。
模型-post.php
class Post extends CI_Model{
function get_posts($num=20, $start=0){
$this->db->select()->from('posts')->where('active',1)->order_by('date_added','desc')->limit($num,$start);
$query=$this->db->get();
return $query->result_array();
}
function get_post($postid){
$this->db->select()->from('posts')->where(array('active' => 1, 'postID'=>$postid))->order_by('date_added','desc');
$query=$this->db->get();
return $query->first_row('array');
}
function insert_post($data){
$this->db->insert('posts',$data);
return $this->db->return_id();
}
控制器-posts.php
class Posts extends CI_Controller{
function __construct(){
parent::__construct();
$this->load->model('post');
}
function index(){
$data['posts'] = $this->post->get_posts();
$this->load->view('post_index', $data);
}
function post($postid){
$data['post']=$this->post->get_post($postid);
$this->load->view('post',$data);
}
function new_post(){
if($_POST){
$data =array(
'title'=>$_POST['title'],
'post'=>$_POST['post'],
'active'=>1
);
$this->post->insert_post($data);
redirect(base_url());
}
else{
$this->load->view('new_post');
}
}
查看-new_post.php
<form action="<?php base_url(); ?>posts/new_post" method="action">
<p>Title: <input type="text" name="title"></p>
<p>Description: <input type="textarea" name="post"></p>
<input type="submit" value="Add post">
</form>
索引视图-post_index.php
foreach ($posts as $post) { ?>
<div id-="container">
<div><h3><a href="<?php base_url(); ?>post/<?php echo $post['postID']; ?>"><?php echo $post['title']; ?> </a></h3>
<?php echo $post['post']; ?>
</div>
</div>
<?php
}
索引页面显示来自 db 的所有帖子。单击标题后,post.php 视图将显示相应的数据。这部分很好。
尝试在 new_post.php 中添加新帖子时,它没有反映在数据库中,也没有显示任何错误。
我还使用redirect_url 在插入后重定向到索引页面。所以它显示了相同的可用帖子。单击标题时,它会不断将 posts/post 重复添加到 url。
重定向网址后点击标题一次显示
再次点击它添加的标题
谁能帮助我?谢谢!
【问题讨论】:
-
我认为您的
base_url设置不正确。如果你去application\config\config.php你为$config['base_url']设置了什么?? -
post_index.php可能有错别字,请看<div id-="container">这一行
标签: php mysql codeigniter post