【发布时间】:2023-03-20 23:56:01
【问题描述】:
目标:
我试图通过按下 html 按钮从我的数据库中的列中减去 0.05。
出了什么问题:
一切正常,它进行了正确的计算并从我的帐户中删除了正确的金额,但它在数据库中的每个帐户上显示了新的金额。
示例:
我的帐户中有 10 个,一旦我按下按钮,我的帐户中现在就有 9.95 个。不幸的是,现在每个人的账户中也都有 9.95!
代码:
Html 按钮和 onclick 脚本:
<button id="playbutton" onclick="myAjax();location.href='5game.html'">Play (-5&#162;)</button>
<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>
减0.05的PHP代码(文件名:subtract5.php):
<?php
session_start();
$servername = "localhost";
$username = "my username"; <not actually this, just confidential
$password = "my password"; <not actually this, just confidential
$dbname = "accounts";
$cash_amount = $_SESSION['cash_amount'];
// Create connection
$userid = $_SESSION['id'];
// 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 = $cash_amount - 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();
?>
预测:
我认为这与用户 ID 字段有关,我不知道该放什么。
数据库布局: 数据库:帐户, 表:用户, 列:id |名字 |姓氏 |电子邮件 |密码 |现金金额 |哈希 |活跃
额外问题:
在我网站的主页上,它显示了现金金额。一旦它被更改,它不会更新,直到我注销并重新登录。有没有什么我可以在顶部的 php 代码中放入诸如“会话重启”之类的东西,以便在每次打开页面时检查新的金额?
谢谢:
非常感谢你的帮助,你可以看到我在这方面有点菜鸟:)
【问题讨论】:
-
您可以通过 POST 将用户
id发送到您的 php 脚本,并在查询中的WHERE子句中使用它
标签: php mysql database html phpmyadmin