Chris Headleand
Chris Headleand

Reputation: 6193

problem with empty values in a database

I have a function which I use all over the place to pull users friends out of a database. However I recently had to delete a few users for causing problems on the forums, this has given me a few "Trying to get property of non-object" problems and I have traced it down to this function.

function isFriend($user_id, $friend_id){
    $this->db->from('friends');
    $this->db->where('user_id', $user_id);
    $this->db->where('friend_id', $friend_id);
    $this->db->where('removed', 0);
    $query = $this->db->get(); 
    $result = $query->result();
    return count($result);
}

Does anyone know how I can adjust this function to ignore deleted users?

Upvotes: 0

Views: 107

Answers (3)

arkleyjoe
arkleyjoe

Reputation: 131

I think the function itself looks fine but it seem likely your errors are caused when the query returns 0 results.

if the removed col in the friends table or the users table?

Maybe you should perform a join to the users table.

Upvotes: 0

No Results Found
No Results Found

Reputation: 102745

If all you're doing is counting the results you can try this instead:

$this->db->count_all_results();

Like this:

function isFriend($user_id, $friend_id)
{
    $num = $this->db
        ->from('friends')
        ->where('user_id', $user_id)
        ->where('friend_id', $friend_id)
        ->where('removed', 0)
        ->from('TABLE_NAME')
        ->count_all_results();

    return $num;
}

It should return 0 if there are no results, whereas $query in your current function (I believe) may not return an object you can call result() on (hence your error).

http://codeigniter.com/user_guide/database/active_record.html

$this->db->count_all_results();

Permits you to determine the number of rows in a particular Active Record query. Queries will accept Active Record restrictors such as where(), or_where(), like(), or_like(), etc. Example:

echo $this->db->count_all_results('my_table'); // Produces an integer, like 25

$this->db->like('title', 'match');
$this->db->from('my_table'); echo
$this->db->count_all_results(); // Produces an integer, like 17

There may be "better" ways, but without knowing the guts of your application it's hard to say.

Upvotes: 1

Dan Bizdadea
Dan Bizdadea

Reputation: 1302

why did you actualy remove them from database when you have the flag "removed" ? Anyway, i think you should also remove the connections of those removed users, i don't see anything wrong with the function.

Trying to alter the function to work, it's just a hack and it's not good practice.

Upvotes: 0

Related Questions