SELECT SUM(total_cost)
FROM purchase;
How do I make the value of SUM(total_cost) to a variable? If SUM(total_cost) = 300, how do I assign 300 to $result for example? I'm trying to do this in coldfusion, but php will work too.
CodePudding user response:
You can completely handle it in the MySQL query:
SELECT SUM(column_name) FROM table_name;
Using PDO (mysql_query
is deprecated)
$stmt = $handler->prepare('SELECT SUM(value) AS value_sum FROM codes');
$stmt->execute();
$row = $stmt->fetch(PDO::FETCH_ASSOC);
$sum = $row['value_sum'];
Or using mysqli:
$result = mysqli_query($conn, 'SELECT SUM(value) AS value_sum FROM codes');
$row = mysqli_fetch_assoc($result);
$sum = $row['value_sum'];
CodePudding user response:
For mysqli
$data = mysqli_query($conn, 'SELECT SUM(value) AS value_sum FROM codes');
$row = mysqli_fetch_assoc($data);
$result = $row['value_sum'];
Now u can get a Sum of value in $result