此问题在此处已有答案:
"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; ?>
2条答案
按热度按时间g52tjvyc1#
在你看来试着这样
代替
a8jjtwal2#
注解控制器中缺少$data中的
comments
。请使用empty()
检查视图中是否存在变量