How to subtract data numbers from a row

i liked to subtract 100 points from user points i have try my self with this code but it replace all points there to -100 how can i subtract 100 points from this row: this row its only numbers: My code:

$sql = mysql_query("UPDATE `users` SET user_points = '$user_points-100' WHERE user_id=".$_SESSION['user']);

Upvotes: 1

Views: 244

Answers (3)

Kostas Mitsarakis
Kostas Mitsarakis

Reputation: 4747

Try to avoid SQL Injection using PDO. Also you don't need the $ symbol in your sql statement.

define('DB_HOST', 'localhost');
define('DB_NAME', 'your_database');
define('DB_USER', 'your_username');
define('DB_PASSWORD', 'your_passworde');

try {
    //Make your connection handler to your database
    $conn = new PDO("mysql:host=".DB_HOST.";dbname=".DB_NAME, DB_USER, DB_PASSWORD, array(PDO::ATTR_ERRMODE => PDO::ERRMODE_WARNING));

    $user_id = $_SESSION['user'];

    $sql = "UPDATE users SET user_points = (user_points - 100) WHERE user_id = :user_id";
    $stmt = $conn->prepare($sql);
    $stmt->execute(array(':user_id'=>$user_id));

} catch(PDOException $e) {
    echo $e->getMessage();
    die();
}

Also, check this information too.

Upvotes: 0

Tommy
Tommy

Reputation: 366

Do it outside the Query, but in the script?

//Take user_points and subtract 100
$user_points = $user_points - '100';
$sql = mysql_query("UPDATE `users` SET user_points = '$user_points' 
WHERE user_id=".$_SESSION['user']);

Upvotes: 0

Eduardo Galván
Eduardo Galván

Reputation: 962

Get rid of the single quotes and the $ symbol, like this:

$sql = mysql_query("UPDATE `users` SET user_points = user_points-100 WHERE user_id=".$_SESSION['user']);

Upvotes: 1

Related Questions