Gaston Velarde
Gaston Velarde

Reputation: 229

MySQL Update with variables in PHP

mysql_connect('localhost', 'root', '')
        or die(mysql_error());
mysql_select_db('shuttle_service_system') 
or die(mysql_error());

$ID_No=$_POST['ID_No'];
$CurrentBalance = $_POST['CurrentBalance'];
$AddedAmount = $_POST['AddedAmount'];
$NewBalance = $CurrentBalance + $AddedAmount;

$sql = ("UPDATE balance
        SET Balance= '$NewBalance' 
        WHERE ID_No= '$ID_No' ");
$result=mysql_query($sql);

if($result){
        echo"Transaction successful!";
} else {
        echo "&nbsp Error";
}

Hi guys I'm trying to update my certain values in my database with the use of variables. It updates when I use brute force and not variables. I know my variables are working because I printed them before queuing the update.

Upvotes: 1

Views: 90

Answers (2)

V Setyawan
V Setyawan

Reputation: 86

You forgot to add (dot) symbol.

$result = mysql_query("UPDATE balance SET Balance='".$NewBalance."' WHERE ID_No='".$ID_No."';");

This approach is bad and you might want to read this post to prevent SQL injection.

Upvotes: 1

Remove the paranthesis outside this UPDATE Statement

$sql = ("UPDATE balance
        SET Balance= '$NewBalance' 
        WHERE ID_No= '$ID_No' ");

It should be

$sql = "UPDATE balance
        SET Balance= '$NewBalance' 
        WHERE ID_No= '$ID_No' ";

Also, add this mysql_error() to read the exact error when your query fails.

$result=mysql_query($sql) or die(mysql_error());

This(mysql_*) extension is deprecated as of PHP 5.5.0, and will be removed in the future. Instead, the MySQLi or PDO_MySQL extension should be used. Switching to PreparedStatements is even more better to ward off SQL Injection attacks !

Upvotes: 1

Related Questions