如何从一行中减去数据

时间:2016-04-12 15:45:05

标签: php mysql

我喜欢从用户点中减去100分我已尝试使用此代码,但它将所有点替换为-100如何从此行中减去100点:此行仅包含数字: 我的代码:



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




3 个答案:

答案 0 :(得分:1)

摆脱单引号和$符号,如下所示:

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

答案 1 :(得分:0)

在Query之外,但在脚本中吗?

//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']);

答案 2 :(得分:0)

尽量避免使用PDO进行SQL注入。此外,您不需要在sql语句中使用$符号。

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();
}

另外,请检查此information