I want to take a current balance and add with previous balance

Asked

Viewed 262 times

-1

This system and to make banking operations the user will have to make the deposit only he enters a value that he wants to deposit and in the bank he will have to add with the current balance only that is not working. he’s putting a number 7 and he’s not making the sum

<?php
$idConta=$_POST['idConta'];
$valor=$_POST['valor'];

$consu= mysql_query("select saldo from conta where  idConta=$idConta");

$saldoatual = $consu + $valor;


$up = mysql_query("UPDATE conta SET saldo='$saldoatual'  WHERE idConta=$idConta");



?>

inserir a descrição da imagem aqui

  • 1

    You don’t even need the SELECT, can do right in the UPDATE in this way UPDATE conta SET saldo = saldo + '$saldoatual' WHERE idConta=$idConta

  • mysql_query returns a reference to a result set, instead of the result set itself, then you stop $consu will have something like Resource id #3. You need to call a function like mysql_fetch_array or mysql_fetch_assoc to read the result itself of the result set object (and what you get is an array). This value: Resource id #3 is the return of a query, indicating tb the position of the memory in which it was allocated

  • Learn more about Resource in https://answall.com/questions/90764/o-que-%C3%A9-a-type-Resource-in-php-to-serve/90771#90771

1 answer

1

Your code is wrong mysql_query does not return data, it returns the handler of the executed query, so one must use mysql_fetch_assoc to take the values, for example:

ps: add isset to check if the variables came via POST correctly

if (isset($_POST['idConta']{0}, $_POST['valor']{1})) {

    $idConta=$_POST['idConta'];
    $valor=$_POST['valor'];
    $up = false;

    $consu = mysql_query("select saldo from conta where  idConta=$idConta");

    if ($consu) {
        $dados = mysql_fetch_assoc($consu);

        $saldoatual = $dados['saldo'] + $valor;

        $up = mysql_query("UPDATE conta SET saldo='$saldoatual'  WHERE idConta=$idConta");
    } else {
         echo 'Erro:', mysql_error();
    }
}

Extra

However, I recommend you update and stop using this API (functions that start with the prefix mysql_) which is already so obsolete, to access your mysql database prefer the new Apis as:

  • PDO
  • mysqli

Browser other questions tagged

You are not signed in. Login or sign up in order to post.