Jose Carrillo
Jose Carrillo

Reputation: 1860

PHP and MySQL using the PDO class

I am trying to update a database, here is my code

if (isset($_GET['placeorder']))
{
    include 'includes/db.php';

    try
    {
    $newBalance = $_POST['balance'] + $_POST['oldbalance'];
    $sql = 'UPDATE customer SET
            balance = :balance
            WHERE id = :id';
    $s = $pdo->prepare($sql);
    $s->bindValue(':balance', $newBalance);
    $s->execute();
    }
    catch (PDOException $e)
    {
        $error = 'Could not add the new balance for the customer' . $e->getMessage();
        include  'result.php';
        exit(); 

    }
    header('Location: .');
    exit();

What I am trying to do is update the balance for a customer that is coming from a form that was submitted. I am able to get the value in the code all the way up to where I get to $s->execute(); if I try to echo the value, which is $newBalance, it will not show after that line is executed, the page goes blank. Something is happening in the execute statement. $s->execute() that it does not allow my code to proceed. Any idea? Am I using the PDO class the wrong way. It is not getting to the "catch" statement. Any help would be great. The end result is that the page returns to where it started with the updated balance.

Upvotes: 1

Views: 115

Answers (2)

doublesharp
doublesharp

Reputation: 27599

You are only binding a value to the balance, not the id, you need a line like:

$s->bindValue(':id', $id);

It would be a good idea to make sure that $_POST['balance'] and $_POST['oldbalance'] are set as well before using them in your query:

$balance = isset($_POST['balance'])? $_POST['balance'] : 0;
$oldbalance = isset($_POST['oldbalance'])? $_POST['oldbalance'] : 0;
$newbalance = $balance + $oldbalance;

If you aren't getting an error, you likely don't have error reporting on, you can enable it by adding error_reporting(E_ALL); to the top of your page.

Upvotes: 1

swapnesh
swapnesh

Reputation: 26722

var_dump() both variables $_POST['balance'] & $_POST['oldbalance']. I am sure they are coming as string. Type casting is one of the solution. Try typecasting in this case to perform addition on int/float.

$newBalance = (int)$_POST['balance'] + (int)$_POST['oldbalance'];

Upvotes: 0

Related Questions