Wednesday 27 June 2012

using mysql count makes me only return 1 row

take a look at this code

   $query_user="select count(id) as total,id,firstname,middlename,lastname,cb_addressline1,cb_addressline2,cb_addressline3,cb_addressline4,cb_postcode,cb_telephone from #__comprofiler where id LIKE'%$find%' or  firstname LIKE'%$find%' or lastname LIKE'%$find%' or cb_telephone LIKE'%$find%' or cb_addressline1 LIKE'%$find%' or cb_addressline2 LIKE'%$find%' or cb_addressline3 LIKE'%$find%' or cb_addressline4 LIKE'%$find%'";
                                 $db->setQuery($query_user);
                               
                                $listdata  = $db->loadObjectList();
                                 //print_r($listdata);
                                 if($listdata[0]->total==0)
                                         {



you'll notice that  'count(id) as total ' is being used to count the results .  However using count() in this way was makiing my results only return 1 row.   Take a look at this post http://stackoverflow.com/questions/4082713/mysql-returns-only-one-row-when-using-count 

So I've now replaced the query for

[code]

  $query_user="select id,firstname,middlename,lastname,cb_addressline1,cb_addressline2,cb_addressline3,cb_addressline4,cb_postcode,cb_telephone, (select count(*) FROM #__comprofiler WHERE id LIKE'%$find%' or  firstname LIKE'%$find%' or lastname LIKE'%$find%' or cb_telephone LIKE'%$find%' or cb_addressline1 LIKE'%$find%' or cb_addressline2 LIKE'%$find%' or cb_addressline3 LIKE'%$find%' or cb_addressline4 LIKE'%$find%') as total from #__comprofiler where id LIKE'%$find%' or  firstname LIKE'%$find%' or lastname LIKE'%$find%' or cb_telephone LIKE'%$find%' or cb_addressline1 LIKE'%$find%' or cb_addressline2 LIKE'%$find%' or cb_addressline3 LIKE'%$find%' or cb_addressline4 LIKE'%$find%'";
                               

[/code]

I then got an error with $listdata[0]->total==0 

after testing the object  $listdata   - as I noticed if the search was empty then I changed the line.

f($listdata[0]->total==0 ) 

to

if($listdata == NULL )


So we don't need to use SELECT count(*) as total - at all .  is it enough just to test the search to see if its NULL.



Which is much simplier

No comments: