-3

I have this query with this php code and can't show the result in echo, I can convert to string?

//conexion is my function to conect to DB and is done


$costTotal=conexion();
$costTotal=$costTotal->query("SELECT SUM(product_cost) FROM product");

echo $costTotal;

For example expected string(5)"18000"

Your Common Sense
  • 156,878
  • 40
  • 214
  • 345
  • You have to call a `fetch` function to fetch a row of results. This should be explained in any PHP mysqli tutorial. – Barmar Aug 16 '23 at 18:37

1 Answers1

-1

$costTotal contains the result of the database query which is not a string but you're using echo. To get the result as a string, you need to fetch the data from the query result.

$connection = connexion();

$query = "SELECT SUM(product_cost) as total FROM product";
$result = $connection->query($query);
$data = $result->fetch(PDO::FETCH_ASSOC);

$costTotal = $data['total']; 

echo $costTotal;
Wakil Ahmed
  • 1,053
  • 1
  • 8
  • 16
  • using FETCH_ASSOC makes no sense in this context – Your Common Sense Aug 16 '23 at 19:06
  • Thanks friends I resolve add fetch function $costTotal=$costTotal->fetch(); Is array and next use $costTotal[0]; to the echo I use var_dump($costTotal) to see the result array(2) { ["SUM(product_cost)"]=> string(8) "27000.00" [0]=> string(8) "27000.00" } – Vincent Edgren Aug 16 '23 at 19:10