I'm new to Codeigniter
and PHP
, just learning. I've searched for this but couldn't find the right answer. I have a table that contain some data, lets call it posts
and in this table, each post have a category_id
. I have another table called categories
and in this table I have 2 columns: id
and name
.
I want to join the two tables that the result I'll get is the same as posts
with another column called category_name
that will be taken from categories.name
. Just can't figure out how to do so.
This is what I was up to so far:
function getPostsWithByCategoryID($numberOfRows, $start, $categoryId)
{
$this->db->select('*');
$this->db->from('posts')->order_by('id','desc')->limit($numberOfRows, $start);
$this->db->where('category_id', $categoryID);
$this->db->join('categories', 'posts.category_id == categories.id');
$query = $this->db->get();
return $query->result_array();
}
Thanks in advance.
========================================================================
EDIT:
After trying Adrian Forsius answer:
function getPostsWithByCategoryID($numberOfRows, $start, $categoryId)
{
$this->db->select('*, category.name AS category_name');
$this->db->from('posts')->order_by('id','desc')->limit($numberOfRows, $start);
$this->db->where('category_id', $categoryID);
$this->db->join('categories', 'posts.category_id = categories.id');
$query = $this->db->get();
return $query->result_array();
}
I'm getting this error:
Error Number: 1054: Unknown column 'category.name' in 'field list'
SELECT *, `category`.`name` AS category_name
FROM (`posts`)
JOIN `categories` ON `posts`.`category_id` = `categories`.`id`
WHERE `category_id` IS NULL
ORDER BY `id` desc
LIMIT 20
====
EDIT 2:
So I found some mistakes in the code and fixed them, tried again, but still I get an error: (The mistakes were using $categoryID
instead of $categoryId
and select category.name
instead of the true name of the table categories
which is categories.name
Error Number: 1052: Column 'id' in order clause is ambiguous
SELECT *, `categories`.`name` AS category_name
FROM (`posts`)
JOIN `categories` ON `posts`.`category_id` = `categories`.`id`
WHERE `category_id` = '3'
ORDER BY `id` desc
LIMIT 20