0

I'm working on a comment section for my blog post in CodeIgniter, I based myself on a tutorial by Brad Traversy and I followed each step carefully but somehow it does not work within my template.

This is show method in my Post Controller:

    public function show($slug)
{
    // Get Posts by Slug
    $data['posts'] = $this->Post_model->get_by_slug($slug);

    // Get Comments per Post
    $post_id = $data['posts']['id']; // Here is where I get the error
    $data['comments'] = $this->Post_model->get_comments($post_id);

    // If empty show a 404 error
    if(empty($data['posts'])){
        show_404(); 
    }

    // Load template
    $this->template->load('public', 'default', 'posts/show', $data);
}

I created a variable $post_id in order to get the comments for the current post that is being visited by an user. All this should come from my Post_model:

    public function get_comments($post_id){

    $this->db->select('username,email,website,body');
    $this->db->from('comments');
    $query = $this->db->get_where('comments', array('post_id' => $post_id));
    return $query->result_array();

}

This is where I'm creating the form to add the comment:

        <!-- Form -->
    <h4>Add a comment</h4>
    <?php echo validation_errors('<p class="alert alert-danger">'); ?>
    <?php echo form_open('public/comments/add_post_comment/'.$post['id']); ?>
    <!-- Username -->
    <div class="form-group">
    <?php echo form_label('Username', 'username'); ?>
    <?php
        $data = array(
            'id'    => 'username',
            'name'  => 'username',
            'class'     => 'form-control',
            'placeholder'   => 'John Doe',
            'value'         => set_value('username')
        );
    ?>
    <?php echo form_input($data) ?>
    </div>        
    <!-- Email -->
    <div class="form-group">
    <?php echo form_label('E-mail', 'email'); ?>
    <?php
        $data = array(
            'id'    => 'email',
            'name'  => 'email',
            'class'     => 'form-control',
            'placeholder'   => 'JohnDoe@demo.com',
            'value'         => set_value('email')
        );
    ?>
    <?php echo form_input($data) ?>
    </div>      
    <!-- Website -->
    <div class="form-group">
    <?php echo form_label('Website', 'website'); ?>
    <?php
        $data = array(
            'id'    => 'website',
            'name'  => 'website',
            'class'     => 'form-control',
            'placeholder'   => 'https://www.example.com',
            'value'         => set_value('website')
        );
    ?>
    <?php echo form_input($data) ?>
    </div>
    <!-- Comments Body -->
    <div class="form-group">
        <?php echo form_label('Body', 'body'); ?>
        <?php
            $data = array(
                'id'            => 'body',
                'name'          => 'body',
                'class'         => 'form-control',
                'placeholder'   => 'Write here',
                'value'         => set_value('body')
            );
        ?>
        <?php echo form_textarea($data); ?>
    </div>
    <!-- Hidden Input -->
    <?php
        $data = array(
            'name'  => 'slug',
            'value' => $posts->slug,
        );
    ?>
    <?php echo form_hidden($data); ?>
    <!-- Submit Button -->
    <?php echo form_submit('mysubmit', 'Add Comment', array('class' => 'btn btn-primary')); ?>
    <?php echo form_close(); ?>
    <?php endif; ?>

This is the Controller I'm using to add comments to the specific $post_id:

    public function add_post_comment($post_id)
{

    // Field Rules
    $this->form_validation->set_rules('email', 'Email', 'trim|required|min_length[3]');
    $this->form_validation->set_rules('body', 'Body', 'trim|required|min_length[3]');

    if ($this->form_validation->run() == FALSE) {

        // Set Message
        $this->session->set_flashdata('error', 'There was an error in proccessing the comment. Please, try again.');

        // Redirect to current page
        redirect(site_url() . 'posts/show/'.$post_id);

    } else {

        // Get Post by Slug
        $slug = $this->input->post('slug');
        $data['posts'] = $this->Post_model->get_by_slug($slug);

        // Create Post Array
        $data = array(
            'post_id'   => $post_id,
            'username'  =>  $this->input->post('username'),
            'user_id'   =>  $this->session->userdata('user_id'),
            'email'     =>  $this->input->post('email'),
            'website'   =>  $this->input->post('website'),
            'body'      =>  $this->input->post('body'),
        );

        // Insert Comments
        $this->Comments_model->add($data);

        // Set Message
        $this->session->set_flashdata('success', 'Your comment has been posted');

        // Redirect to same page if form was not successful or submitted
        redirect(site_url() . 'posts/show/'.$post_id);

    }
}

All this should work according to some tutorials that I have seen before but this time is not.

enter image description here

The error comes from my function show. Any idea on how to fix this? Thanks for helping.

Kirasiris
  • 523
  • 10
  • 37
  • 1
    it already says _cannot use object of type stdClass as an array_, it means `$data['posts']` is an object not an array – Kevin Jan 22 '18 at 07:18
  • simple sentence: it is not an array, it is object.. – Pathik Vejani Jan 22 '18 at 07:19
  • @Kevin Am I going blind or have you forgotten to include the code for your Post_model method - get_by_slug? As you indicate that is the cause of your issue. – TimBrownlaw Jan 22 '18 at 07:26
  • In your show function - add a var_dump($data['posts']); right after your call to get_by_slug so you can eyeball what it's returning. – TimBrownlaw Jan 22 '18 at 07:28
  • I already have the method(get_by_slug) on my Post_model: Here is what I have: `public function get_by_slug($slug) { $this->db->select('*'); $this->db->from($this->table); $this->db->where('slug', $slug); $this->db->where('is_published', 1); $this->db->limit(1); $query = $this->db->get(); if ($query->num_rows() == 1) { return $query->row(); } else { return false; } }` – Kirasiris Jan 22 '18 at 07:32
  • Possible duplicate of [Cannot use object of type stdClass as array?](https://stackoverflow.com/questions/6815520/cannot-use-object-of-type-stdclass-as-array) – Jigar Shah Jan 22 '18 at 09:02
  • I already fixed but thanks anyway. – Kirasiris Jan 22 '18 at 21:44
  • @Kevin So "Fixed" means you got it working? If so, what did you do? – TimBrownlaw Jan 22 '18 at 23:00
  • I changed `$post_id = $data['posts']->id;` as you suggested and from there I went into my view and I changed `$comment->username` to `$comment['username']` and it worked like a charm. In addition to that ` public function get_comments($post_id){ $this->db->select('*'); $query = $this->db->get_where('comments', array('post_id' => $post_id)); if($query->num_rows() > 0) { return $query->result_array(); } else { return false; } }` – Kirasiris Jan 23 '18 at 02:45

1 Answers1

0

Ok well as you would have read in the codeigniter users guide - $query->row() will return an object.

So you would use $data['posts']->id. Which may or may not work with your current PHP Version. I'm open to be corrected on that point.

If you want an associative array, as you are attempting to use, then you would use $query->row_array();

If you had performed a var_dump like...

public function show($slug)
{
    // Get Posts by Slug
    $data['posts'] = $this->Post_model->get_by_slug($slug);

    // Quick Debug to Eyeball what is actually being returned.
    var_dump($data['posts']);
    exit();

    // Get Comments per Post
    $post_id = $data['posts']['id']; // Here is where I get the error
    $data['comments'] = $this->Post_model->get_comments($post_id);

    // If empty show a 404 error
    if(empty($data['posts'])){
        show_404(); 
    }

    // Load template
    $this->template->load('public', 'default', 'posts/show', $data);
}

You would see ( and its always a good check when validating your code ) what is being returned by $this->Post_model->get_by_slug($slug);

It's a very good idea to know how to "look" at what your variables are and check they are what you think they should be.

TimBrownlaw
  • 5,457
  • 3
  • 24
  • 28