Help with SELECT statement

Hi,

I am trying to select ALL the values in one of the columns in my db where a certain condition is met, but I only seem to get 1 result and not an array of results, any ideas? see below:

<?php
 $query_c1 = "SELECT main FROM orders WHERE dh_code= 'my cd'";
$db_charity = dbQuery($query_c1);
while($fetch_charity=mysql_fetch_array($db_charity)){
echo $fetch_charity[0];
}
										
?>

Code looks fine; I’d say there really is just one order where the dh_code is ‘my cd’.

sorry, what I wanted is to add the values together, I revised the code (see below) but brings up an error message

$query_c1 = "SELECT order_price FROM orders WHERE  dh_code = 'my cd'";
											$db_charity = dbQuery($query_c1);
											$charity_sum = array_sum(mysqli_fetch_array($db_charity));
											echo $charity_sum;

In what format is the value of order_price?

it is decimal(15,2) - they are numbers like 29.95. I want to take all these numbers where a specific column equals ‘my cd’. Then I want to calculate the total - that is why I am using array_sum, but I dont think its in the right place…

why not let the database do the sum for you?

SELECT SUM(order_price) AS total_price
  FROM orders 
 WHERE dh_code = 'my cd'        

You’re right, it’s not :slight_smile:

mysql_fetch_array() only returns an array of one of the rows, what you want is the sum of all of the rows. So you’d have to loop all rows first and store the values in an array and array_sum that one, or keep a variable and add the price to it for every row. So, you could either do this –


$query_c1 = "SELECT order_price FROM orders WHERE  dh_code = 'my cd'";
$db_charity = dbQuery($query_c1);
$data=array();
while($row=mysqli_fetch_array($db_charity)) {
   $data[] = $row[0];
}
$charity_sum = array_sum($data);
echo $charity_sum;  

– or this –


$query_c1 = "SELECT order_price FROM orders WHERE  dh_code = 'my cd'";
$db_charity = dbQuery($query_c1);
$charity_sum=0;
while($row=mysqli_fetch_array($db_charity)) {
   $charity_sum += $row[0];
}
echo $charity_sum;

– but actually you should not use either of those, but rather use the suggestion Rudy (r937) just suggested; it’s ~far~ better than either of the solutions above :slight_smile: