0

I am fairly new to php so i'm looking for a bit of direction. I am query sql server and i need to do a sum on some of the columns. If i use the array 1,2,3 that works but i don't seem to be able to get the values for impressions_total.

$sql = "SELECT * FROM dash_g_adwords_csv";
$stmt = sqlsrv_query($conn, $sql);
if( $stmt === false) {
   die( print_r( sqlsrv_errors(), true) );
}

//while($row = sqlsrv_fetch_rows($stmt)){
while( $row = sqlsrv_fetch_array( $stmt, SQLSRV_FETCH_BOTH) ) {
   //print_r($row);
   $impressions_total = array('impressions_total', 'impressions_image', 'impressions_search'); 
   //$impressions_total = array(1, 2, 3); 
   //$click_total = array('$click_text', '$click_image', '$click_search');

   echo
   "<tr><td>" . $row['brand'] .
   "</td><td>" . $row['period'] .
   "</td><td>" . array_sum($impressions_total) .
   "</td><td>" . array_sum['$click_total'] .
   "</td></tr>";
}
sqlsrv_free_stmt( $stmt);
brombeer
  • 8,716
  • 5
  • 21
  • 27
Rich Walker
  • 33
  • 10
  • Your `$impressions_total` array is an array of strings and not numbers, that's why `array_sum` doesn't work. Could you specify whether your database stores impressions_total as a prepared value, or you need the sum of `impressions_total`, `impressions_image` and `impressions_search`? – Ivan T. Apr 16 '18 at 10:03

2 Answers2

1
 $impressions_total = array('impressions_total', 'impressions_image', 'impressions_search'); 

This LOC makes your impressions_total an array of strings rather than an array of integer or numbers.

array_sum 

Only works with an array of numbers.

Farhan Qasim
  • 990
  • 5
  • 18
1

You try to sum an string-array which is not working!

It looks like you want to sum the impressions and clicks. So you can use the following:

while ($row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_BOTH)) {
    $impressions_total = [$row['impressions_total'], $row['impressions_image'], $row['impressions_search']];
    $click_total = [$row['click_text'], $row['click_image'], $row['click_search']];

   echo
   "<tr><td>" . $row['brand'] .
   "</td><td>" . $row['period'] .
   "</td><td>" . array_sum($impressions_total) .
   "</td><td>" . array_sum($click_total) .
   "</td></tr>";
}
Sebastian Brosch
  • 42,106
  • 15
  • 72
  • 87
  • @rosuandreimihai - this solution creates the sum of impressions per line (per period and brand). To get the sum of all impressions and clicks we need to sum the totals and echo outside `while`. – Sebastian Brosch Apr 16 '18 at 10:19