Home  >  Q&A  >  body text

How to display single SQL query results in PHP

<p>I have a query about this php code and cannot display the results in echo, can I convert to string? </p> <pre class="brush:php;toolbar:false;">//conexion is my function to connect to the database and has been completed $costTotal=conexion(); $costTotal=$costTotal->query("SELECT SUM(product_cost) FROM product"); echo $costTotal;</pre> <p>For example, the desired result is <code>string(5)"18000"</code></p>
P粉852578075P粉852578075451 days ago549

reply all(1)I'll reply

  • P粉797004644

    P粉7970046442023-08-18 09:57:17

    $costTotal contains the result of the database query, it is not a string, but you are using echo. To output the results as a string, you need to get the data from the query results.

    $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;

    reply
    0
  • Cancelreply