Welcome Guest, Not a member yet? Register   Sign In
Negation in Database Query
#1

[eluser]nicholas.byfleet[/eluser]
Hello. I am trying to show "related posts" in a blogging module of my own CI CMS. This related post section is just a list of 5 of the most recent posts in the same category as the current post being shown. Here is some of the code in my view:

Code:
&lt;?php echo "<h3>{$category->name}</h3><p>{$category->description}</p>";
$this->db->select('id', 'title');
$this->db->order_by('date', 'desc');
$query = $this->db->get_where('posts', array('status' => 'active', 'category' => $category->id), 5, 0);
if ($query->num_rows()) {
    echo "<h3>Related Posts</h3><ul>";
    foreach ($query->result_array() as $post) {
        echo "<li><a >{$post['title']}</a></li>";
    }
    echo "</ul>";
}
?&gt;

Here's my question: I want to exclude the current post being viewed from the list and was wondering if there is a way to use active record syntax to specify negation in the get_where statement. In normal SQL, I might write:
Code:
$sql = "SELECT * FROM `posts` WHERE `category`='".$category->id."' AND `id` != '".$id."' LIMIT 0,5 ORDER BY `date` DESC;";
In active record syntax, how do I acheive this part of the SQL?:
Code:
AND `id` != '".$id."'
Do you understand my question? I hope I have explained my problem with clarity. In any case, I hope someone can provide some advice. Thanks in advance.
#2

[eluser]nicholas.byfleet[/eluser]
Oh, and I just caught my $this->db->select(); error. Sorry for that.
#3

[eluser]mah0001[/eluser]
Try:
Code:
$this->db->where('id !=', $id);//ID of the post you want to exclude
$query = $this->db->get_where('posts', array('status' => 'active', 'category' => $category->id), 5, 0);
#4

[eluser]nicholas.byfleet[/eluser]
Perfect! Thanks so much for this tip. This would be a good thing to include in the documentation methinks.
#5

[eluser]mah0001[/eluser]
It is already in the documentation. see http://ellislab.com/codeigniter/user-gui...ecord.html
#6

[eluser]nicholas.byfleet[/eluser]
Wow, i feel like an idiot. Believe it or not I did read through the documentation before posting my question, however, since I wanted to condense the code into a get_where statement, I overlooked the where method documentation. In any case, thanks again!




Theme © iAndrew 2016 - Forum software by © MyBB