php - 按html按钮后如何从mysql数据库中减去?

标签 php mysql

一旦玩家按下按钮,我就会尝试从数据库中玩家的现金金额中减去 0.05。这是我到目前为止所得到的。

我的数据库:

数据库名称:帐户

表:用户

我想要影响的列:cash_amount

HTML:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script type = "text/javascript">
function myAjax () {
$.ajax( { type : 'POST',
            data : { },
            url  : 'subtract5.php',              // <=== CALL THE PHP FUNCTION HERE.
            success: function ( data ) {
                alert( data );               // <=== VALUE RETURNED FROM FUNCTION.
            },
            error: function ( xhr ) {
                alert( "error" );
            }
        });
}
</script>


<button id="playbutton" onclick="myAjax();location.href='5game.html'">Play (-5&#162;)</button>

PHP 文件:(subtract5.php)

<?php

 UPDATE `accounts`.`users` SET `cash_amount` = '`cash_amount` - 0.05'

感谢您的帮助,我是个菜鸟:)

最佳答案

这是以下代码,但是不要完全复制粘贴它,请阅读注释,您可能需要更改一些变量并从数据库中获取。

<?php
$servername = "servarname";
$username = "username";
$password = "password";
$dbname = "dbName";

// Create connection

$userid = // You must enter the user's id here.

$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection

if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
} 

// Fetch the existing value of the cash_amount against that particular user here. You can use the SELECT cash_amount from users where userid = $userid

$newAmount = $previousAmount - 0.05;

$sql = "UPDATE users SET cash_amount = '$newAmount'";
$result = $conn->query($sql);

if($result)
{
   echo "Query Executed Successfully!";
}
else
{
   echo mysqli_error($conn);
}

$conn->close();
?>

关于php - 按html按钮后如何从mysql数据库中减去?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45184334/

相关文章:

php - 为 View 使用替代结构时出错

php - 根据存储的 cookie 信息将用户重定向到网站

php - 开发业务代码时应该使用 IoC 依赖注入(inject)吗?

javascript - 在 NodeJS 中导出 API 对象

php - INSERT INTO 电子邮件地址中的 MySQL 语法错误

php - Symfony 国际化

java - 在Java中是否有一个array_intersect()等效项?

python - SQL 不显示更新的表

mysql - 数据迁移停止后急救致命mysql服务器错误

java.sql.SQLException : No suitable driver found for jdbc:mysql://localhost:3306/sushi 异常