I have three tables
I have a code as follows:
my posts controller
$data['all_categories'] = $this->category_model->get_all_categories();
$data['posts'] = $this->post_model->get_posts();
$data['users'] = $this->user_model->get_user();
$this->load->view('pages/template', $data);
my post_model
$this->db->order_by('posts.id', 'DESC');
$this->db->join('categories', 'categories.id = posts.category_id');
$this->db->join('users', 'users.id = posts.user_id');
$query = $this->db->get('post');
return $query->result_array();
my index view
<?php foreach ($posts as $post): ?>
<br>
<div class="media">
<div class="media-body" style="margin-left: 5px;">
<h5><?php echo $post['title']; ?></h5>
<small class="post-date"><span class="fa fa-user"></span> <strong><?php echo $post['username']; ?></strong> | <span class="fa fa-tags"></span> <strong><?php echo $post['name']; ?></strong></small><br>
<?php echo character_limiter($post['content'], 250); ?>
<hr>
</div>
</div>
<?php endforeach; ?>
I successfully displayed it in index view, but username and category name doesn't work in single post.
My post view
<h5><?php echo $post['title']; ?></h5>
<small class="post-date"><span class="fa fa-user"></span> <strong><?php echo $post['username']; ?></strong> | <span class="fa fa-tags"></span> <strong><?php echo $post['category_id']; ?></strong></small><br>
<?php echo $post['content']; ?>
Please help me guys. Thanks!
Add following code in your files.
In Model
public function load_posts(){
$this->db->select('tbl_p.*, tbl_u.username, tbl_u.pass, tbl_c.name as category_name');
$this->db->from('posts as tbl_p');
$this->db->join('users as tbl_u', 'tbl_u.id = tbl_p.user_id', 'left');
$this->db->join('categories as tbl_c', 'tbl_c.id = tbl_p.cat_id', 'left');
$this->db->order_by('tbl_p.id', 'DESC');
$query = $this->db->get();
return ($query->num_rows() > 0) ? $query->result_array() : false;
}
In Controller
$data['posts'] = $this->post_model->load_posts();
Probably is because of same row name. Use SELECT AS 'unique_name' for every row you are selecting.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.