【发布时间】:2018-12-05 15:37:33
【问题描述】:
问题:
我正在尝试从名为 users 的数据库中的变量 cash_amount 中减去 0.05,并且我正在通过 ajax 调用此文件,但没有发生任何事情。为了解决这个问题,我在浏览器中打开了文件,我收到了这个错误:
错误:
您的 SQL 语法有错误;检查与您的 MySQL 服务器版本相对应的手册,以获取正确的语法,以便在第 1 行的 '' 附近使用
代码:
PHP:
<?php
session_start();
$servername = "localhost";
$username = "myUser";
$password = "myPass";
$dbname = "myDBname";
$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
$_SESSION['cash_amount'] -= 0.05;
$newAmount = $cash_amount - 0.05;
$sql = "UPDATE users SET cash_amount = $newAmount WHERE id = $userid";
$result = $conn->query($sql);
if($result)
{
echo "5 cents have been subtracted!";
}
else
{
echo mysqli_error($conn);
session_start();
session_unset();
session_destroy();
}
$conn->close();
?>
Javascript/AJAX:
function countdownEnded() {
//make serverscreen dissapear
document.getElementById('serverScreenWrapper').style.display = 'none';
document.getElementById('serverScreenWrapper').style.opacity = '0';
document.getElementById("cashOutNumTwo").style.right = '150%';
document.getElementById("cashOutNumOne").style.right = '150%';
//start Timer
setInterval(gameTimer.update, 1000);
//make player move again
socket.emit('4');
socket.emit('6');
//make game appear
document.getElementById('gameAreaWrapper').style.opacity = 1;
//play sound
document.getElementById('spawn_cell').play();
//cut 5 cents from account - php function
$.ajax({
type: "POST",
url: 'http://cashballz.net/game/5game/subtract5.php',
data: { },
success: function (data) {
alert(data);
}
});
}
我的数据库:
我的表名为 users,它位于 DB casball_accounts 中。
格式如下:
标识 |名字 |姓氏 |电子邮件 |密码 |现金金额 | 4 之间 |哈希 |活跃
结论:
我很困惑为什么我的 php 代码不起作用,我已经尝试过寻找修复程序,但我找到了“SQL 注入”这个词,但我仍然没有找到错误。我在 JS 方面很先进,但对 PHP 是初学者,所以请多多包涵。谢谢!
【问题讨论】:
-
您确认
id和cash_amount在$_SESSION中正确找到了吗? -
$sql = "UPDATE users SET cash_amount = cash_amount - 0.05 WHERE id = $userid"; -
@RiggsFolly 所以这是可行的,但由于某种原因,我必须注销然后在使用它来更新金额时重新登录,你知道为什么吗?
-
嗨,注销什么?
-
没关系我修好了,我想给你贴上正确答案的标签,但你是评论
标签: php mysql ajax html phpmyadmin