I have a PHP pagination script which works fine, however when i try to group the results the pagination system doesn't account for this and produces to many pages.

I think i know how this is happening, the code uses to queries the first, counts the results and then the second grabs the data for the results.

The problem i am having is that i don't know how to write the first query or if i can to calculate the grouping of the results. Please see the code below.

PHP Code:
$query "SELECT COUNT(*) as num FROM $tableName WHERE client_id = '{$client_id}' AND search_term IS NOT NULL AND search_term != ''";
$total_pages mysql_fetch_array(mysql_query($query));
$total_pages $total_pages[num];
$stages 3;
$page mysql_escape_string($_GET['page']);
$start = ($page 1) * $limit
$start 0;    
// Get page data
$query1 "SELECT search_term, COUNT(search_term) as count FROM $tableName WHERE client_id = '$client_id' AND search_term IS NOT NULL AND search_term != ''  LIMIT $start, $limit";
$result mysql_query($query1); 
Please view the link for a demo


Any suggestions would be greatly appreciated.