I’m attempting to retrieve a sum from a database using PHP, but I am unable to output the result correctly using echo. I need to transform the query result into a string that can be displayed. I am hoping to see something like:
string(5) "18000"
Below is an alternative code example that might help illustrate a working approach:
<?php
// myConnect establishes a connection to the database
$dbHandle = myConnect();
// Execute a query to calculate the total
$resultSet = $dbHandle->query("SELECT SUM(item_price) AS total FROM items");
// Retrieve the result as an associative array
$data = $resultSet->fetch(PDO::FETCH_ASSOC);
// Echo the total cost
echo $data['total'];
?>
This code should help you see how to properly fetch and display the aggregated result from a SQL query in PHP.