I have the following code in a CI app :
$query = "INSERT INTO user(user_name,user_email) VALUES(?,?)";
$result = $this->db->query($query,array($userName,$email));
if ($result->num_rows()>0)
return $this->db->insert_id();
else
return null;
This yields an error ; Fatal error: Call to a member function num_rows() on a non-object in C:\xampp\htdocs\cmdline\application\models\mlogin.php on line 38
line 38 is the condition for number of rows is greater than 0 .
Now I don’t get what is happening – I am using CI’s documentation to check whether number of rows is greater than 0 , why does this fail ?
It’s because you’re doing an
INSERTquery. Queries that modify data returnTRUEin all cases, so what you’re really attempting isTRUE->num_rows(), which doesn’t make any sense, causing an error.What you actually want to check is
$this->db->affected_rows(), which will tell you how many rows were inserted into the database.Although you’re not doing it in this case, it’s worth noting that
affected_rows()will only return the count of rows that actually changed during the query, soUPDATEqueries that don’t actually modify data (i.e. if the field already has the value the query is trying to set it to), then that row won’t be reflected in theaffected_rows()value.