Search code examples
phpmysqlsmartywhere-clause

Smarty Where Clause Not Filtering Data


I am trying to Display all Data Based on a Where Statement but it is showing all the data from the table. Below is my account.php file code

$sql = "SELECT Country,COUNT(*) as count, ROUND(100.0*COUNT(ip)/(SELECT     count(ip)  FROM ip_ptc),2) as percentage  FROM ip_ptc GROUP BY Country


UNION ALL

SELECT 'SUM' ip, COUNT(ip) as sum,'100%'
FROM ip_ptc  WHERE ad_id=" . $db->real_escape_string($input->gc['aid']); 

$result = mysql_query($sql) OR die(mysql_error()); 
while($row = mysql_fetch_assoc($result)) 
{ 
$data[] = $row; # $data is the array created for use in the Smarty template. 
} 
$smarty->assign('data', $data); 
//showing data for addstate

$smarty->assign("file_name", "ptcmaxclicks.tpl");
$smarty->display("account.tpl");
$db->close();
exit();

Checking to url it is passing gc['aid'] accordingly but showing all the data from the table not according to gc['aid'] and in my account.tpl file i have following code

{foreach from=$data item=item key=key} 
<tr>
   <td>{$item.Country}</td> <td>{$item.count}</td> <td>{$item.percentage}</td> 
<tr> 
{/foreach} 

what's wrong i am doing? thanks


Solution

  • Your problem is that the WHERE clause only applies to the second SELECT. You need to add it to the first SELECT too i.e.:

    $sql = "SELECT Country, COUNT(*) as count, 
                ROUND(100.0*COUNT(ip)/(SELECT count(ip)  FROM ip_ptc),2) as percentage
            FROM ip_ptc 
            WHERE ad_id=" . $db->real_escape_string($input->gc['aid']) . 
           " GROUP BY Country
            UNION ALL
            SELECT 'SUM' ip, COUNT(ip) as sum,'100%'
            FROM ip_ptc
            WHERE ad_id=" . $db->real_escape_string($input->gc['aid']);