Georgie Lyme
Georgie Lyme

Reputation: 1

SQL Update query using variables

I am writing php to update a user's balance, but my UPDATE query seems to be throwing an error when it is executed.

    $student = $database->quote($_POST ["studentID"]);
    $amount = $database->quote($_POST ["update_balance"]);

    //sets query to update user balance
    $query = "UPDATE `User` SET `balance`= (`.$amount.`) WHERE `userID`= (`.$student.`)";
    //excecutes the query
    $database->exec($query);

The 'studentID' and 'update_balance' are names of input fields being captured in the HTML.

Upvotes: 0

Views: 322

Answers (2)

Tacsiazuma
Tacsiazuma

Reputation: 776

You should use prepared statements as it's considered much safer than any string escaping mechanism:

$statement = $somePdoInstance->prepare("UPDATE user SET balance = :balance WHERE userId = :user_id");
$statement->execute(array(
   "balance" => $amount, // the values from POST
   "user_id" => $student
));

Now your update query should work fine and it's much safer.

Upvotes: 0

Aniruddha Chakraborty
Aniruddha Chakraborty

Reputation: 1867

remove (`. things . and run sql query

$query = "UPDATE `User` SET `balance`= '$amount' WHERE `userID`= '$student'";

Upvotes: 1

Related Questions