codeigniter 为什么我在没有添加姓名和/或正文的情况下提交评论时会出现此错误?[duplicate]

093gszye  于 2022-12-07  发布在  其他
关注(0)|答案(2)|浏览(73)

此问题在此处已有答案

"Notice: Undefined variable", "Notice: Undefined index", "Warning: Undefined array key", and "Notice: Undefined offset" using PHP(29个答案)
8个月前关闭。
我正面临这个问题(请检查图片)。我想当我点击“提交”没有输入正文和/或电子邮件,以显示这些字段是必填的。我目前是一个初学者,我已经试图处理错误,但我不能。请帮助。

这是我的模型:

<?php 
  class Comment_model extends CI_Model {
public function __construct() {
    $this->load->database(); //database library loaded
}

public function create_comment($post_id) {
    $data = array(
        'post_id' => $post_id,
        'name' => $this->input->post('name'),
        'body' => $this->input->post('body')

    );

    return $this->db->insert('comments', $data);
}

public function get_comments($post_id){
    $query = $this->db->get_where('comments', array('post_id' => $post_id));
    return $query->result_array();
}

}
这是我的评论控制器:

<?php 
  class Comments extends CI_Controller {
  public function create($post_id) {
    $slug = $this->input->post('slug');
    $data['post'] = $this->post_model->get_posts($slug);

    $this->form_validation->set_rules('name', 'Name', 'required');
    $this->form_validation->set_rules('body', 'Body', 'required');

    if($this->form_validation->run() === FALSE) {
        $this->load->view('templates/header');
        $this->load->view('posts/view', $data);
        $this->load->view('templates/footer');

    }
    else {
        $this->comment_model->create_comment($post_id);
        redirect('posts/'.$slug);
    }
}

}
岗位负责人:

public function view($slug = NULL) {
       $data['post'] = $this->post_model->get_posts($slug);

    $post_id = $data['post']['id'];
    $data['comments'] = $this->comment_model->get_comments($post_id);
    
    if(empty($data['post'])){
        show_404();
    }

    $data['title'] = $data['post']['title'];
    $this->load->view('templates/header');
    $this->load->view('posts/view', $data);
    $this->load->view('templates/footer');
}

与视图:code

<h3>Comments</h3>
<?php if($comments) : ?>
    <?php foreach($comments as $comment) : ?>
        <div class="jumbotron bg-dark">
            <h5><?php echo $comment['body']; ?> [by <strong><?php echo $comment['name']; ?></strong>]</h5>
        </div>
    <?php endforeach; ?>

<?php else : ?>
    <p>No Comments to Display</p>
<?php endif; ?>
g52tjvyc

g52tjvyc1#

在你看来试着这样

<?php if(!empty($comments)) : ?>

代替

<?php if($comments) : ?>
a8jjtwal

a8jjtwal2#

注解控制器中缺少$data中的comments。请使用empty()检查视图中是否存在变量

相关问题