简体   繁体   中英

simplest explanation of $query->row() and $query->result()

I'm quite annoyed with CI's behavior lately, may be because i'm little ignorant towards small stuff, now to the question :D. i'm making an application where i'm trying to get one single row using active records, now as a good programmer(i think) i try this when i select such as login

if($query->num_rows() == 1)
{
    // do something
}
// now when i make an update, that also a single row i tend to use this command
if($query->affected_rows() == 1)
{
   // perform some action
}
// now i use this code when i've to get all entries of one single user
if($query->num_rows() > 0)
{
   // show them
}

now many time i get error like "Call to member function num_rows() on non object" can anyone please explain what to use, when to use and how to use, so that code igniter never gets made a me

1.num_rows()

num_rows() are result helper functions , they are used against a query resultobject , note that we don't use it like $this->db->num_rows() , instead we use it like:

$query = $this-query('query'); 

OR

$query = $this->db->get('tableName');

if($query->num_rows()>0){ ....}  

Now lets see affected_rowS().

2. affected_rows()

affected_rows is a query helper function , they are used like $this->db->affected_rows() . Note that $this->db->affected_rows() yields valid result only after a valid db write operation. ie insert, update and delete. The database class has a small hack that allows it to return the correct number of affected rows after a delete operation because MySQL "DELETE FROM TABLE" returns 0 affected rows.

3.$query->result()

This function returns the query result as an array of objects, or an empty array on failure. ie if you have more than one result you have to loop the result object like :

foreach ($query->result() as $row){....}

4.$query->row()

This function returns a single result row as an object. If your query has more than one row, it returns only the first row .

I hope my explanation is readable enough.. Although you could find all of these in CI docs with relevant examples.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM