Search code examples
phpmysqlmysqliprepared-statement

How to add one number to another taken from mysql in php?


Here is the problem: php

$stmt = $con->prepare('SELECT balance,balanceusd FROM accounts WHERE id = ?'); 
$stmt->bind_result($balance,$balanceusd,);

html part

<?=$balanceusd + $balance?>

but when i do it like this, it does not display the 2 values added up to each other. I could use echo, but this page has some extra content to display, so that is not practical for me. Is there any way to add these numbers within the page? Thanks for help!


Solution

  • You need to call $stmt->execute() and $stmt->fetch() to execute the query and fetch the result row into the variables.

    You also can do the addition in the query rather than PHP.

    $stmt = $con->prepare('SELECT balance + balanceusd AS total FROM accounts WHERE id = ?'); 
    $stmt->bind_param("i", $userid);
    $stmt->execute();
    $stmt->bind_result($total);
    $stmt->fetch();
    <?= $total ?>