shank shank - 2 months ago 19
MySQL Question

Where and clause in codeigniter for voting system

I am implementing a voting system in codeigniter: The problem is that everytime a user clicks on upvote

$this->db->set('up', 'up+1', FALSE);
is executed and up is incremented by one. But it should only increment if
count == 0
.

My Model code is :

public function up_votes($id,$ip) {

$query = $this->db->query("SELECT * FROM voting_ip WHERE open_id_fk='$id' and ip_add='$ip';");

$result = $query->row_array();
$count = $result['COUNT(*)'];

if($count == 0) {
$this->db->set('up', 'up+1', FALSE);
$this->db->where('open_id', $id);
$this->db->update('country');
}

}

Answer

Instead of count you use $query->num_rows()

MODEL

public function up_votes($id,$ip) {  
    $query = $this->db->query("SELECT * FROM voting_ip WHERE open_id_fk='$id' and ip_add='$ip'");  
   $count= $query->num_rows();
    if($count == 0) {
        $this->db->set('up', 'up+1', FALSE);
        $this->db->where('open_id', $id);
        $this->db->update('country');
        return TRUE;
    }else{
         return FALSE;
     }

}