Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Codeigniter active record statement not running when sql query doesn't return anything

I seem to be having a problem with the below code. I cannot get the insert query to run when the query returns nothing. But when there is a row in the db, the else statement runs correctly. Does anybody know why this could be happening?

$query5 = $this->db->get_where('loggedstatus', array('userid_loggedstatus' => $userid));

if ($query5->num_rows() < 0) {
    $data1 = array('isLoggedIn_loggedstatus' => 'yes', 'userid_loggedstatus' => $userid);
    $this->db->insert('loggedstatus', $data1);
} else {
    $data = array('isLoggedIn_loggedstatus' => 'yes');
    $this->db->where('userid_loggedstatus', $userid);
    $this->db->update('loggedstatus', $data);
}
like image 590
Michael Grigsby Avatar asked Dec 19 '12 01:12

Michael Grigsby


2 Answers

Have you tried changing this if ($query5->num_rows() < 0) { to something like if ($query5->num_rows() <= 0) {, just a thought. It would make a difference because your telling it to only execute if its less than zero however it might be equal to zero and you would skip to the else statement.

And just for CodeIgniter num_rows() reference:

/**
 * Number of rows in the result set
 *
 * @return  int
 */
public function num_rows()
{
    if (is_int($this->num_rows))
    {
        return $this->num_rows;
    }
    elseif (count($this->result_array) > 0)
    {
        return $this->num_rows = count($this->result_array);
    }
    elseif (count($this->result_object) > 0)
    {
        return $this->num_rows = count($this->result_object);
    }

    return $this->num_rows = count($this->result_array());
}
like image 167
PhearOfRayne Avatar answered Nov 06 '22 12:11

PhearOfRayne


Changing if condition shown below should fix the problem.

if ($query5->num_rows() == 0)
like image 7
vivek Avatar answered Nov 06 '22 13:11

vivek