title: use string variable as query in codeigniter
body: <p>i am using codeigniter and i need to use aggregate function in query. so i have this query.  </p>
  
  <pre><code>"SELECT Dated, CASE WHEN `Account_ID` = 2 then SUM(Total_Bricks) ELSE 0 end as 'Nadeem', 
  CASE WHEN Account_ID = 2 then SUM(Kaat_Bricks) ELSE 0 end as 'NadeemKaat', 
  CASE WHEN `Account_ID` = 7 then SUM(Total_Bricks) ELSE 0 end as 'Abid', 
  CASE WHEN Account_ID = 7 then SUM(Kaat_Bricks) ELSE 0 end as 'AbidKaat', 
  CASE WHEN `Account_ID` = 8 then SUM(Total_Bricks) ELSE 0 end as 'Sajid', 
  CASE WHEN Account_ID = 8 then SUM(Kaat_Bricks) ELSE 0 end as 'SajidKaat' 
  FROM `tblstockdetail` GROUP BY `Dated`"
  </code></pre>
  
  <p>i have generated this query through a simple foreach loop </p>
  
  <pre><code>$stock = $this-&gt;Kharkaar_Model-&gt;get_stockdetail();
  
          $sql = '"SELECT Dated, ';
  
          $numItems = count($stock);
          $i = 0;
          foreach ($stock as $key =&gt; $value) 
          {
  
              if(++$i === $numItems)
              {
                  $sql.= "CASE WHEN `Account_ID` = ".$value['Account_ID']." then SUM(Total_Bricks) ELSE 0 end as '".$value['AccountName']."', &lt;br /&gt; 
              CASE WHEN Account_ID = ".$value['Account_ID']." then SUM(Kaat_Bricks) ELSE 0 end as '".$value['AccountName']."Kaat' &lt;br /&gt; FROM `tblstockdetail` GROUP BY `Dated`";
              }
              else
              {
                  $sql.= "CASE WHEN `Account_ID` = ".$value['Account_ID']." then SUM(Total_Bricks) ELSE 0 end as '".$value['AccountName']."', &lt;br /&gt; 
              CASE WHEN Account_ID = ".$value['Account_ID']." then SUM(Kaat_Bricks) ELSE 0 end as '".$value['AccountName']."Kaat', &lt;br /&gt; ";
  
              }
  
          }
  
          $sql.= '"';
  </code></pre>
  
  <p>now when i try to get result of this query </p>
  
  <pre><code>$result = $this-&gt;db-&gt;query($sql);
  </code></pre>
  
  <p>it is giving me a syntax error, otherwise when i put this query direct into </p>
  
  <pre><code>$result = $this-&gt;db-&gt;query(// string query here );
  </code></pre>
  
  <p>it is running fine.</p>