【发布时间】:2019-12-31 16:40:37
【问题描述】:
我想将值“totalscore”从我的 JavaScript 代码存储到我的数据库中。我尝试使用 ajax 调用但有些东西不起作用,我以前没有使用过 ajax。
在下面的 JavaScript 代码中,我将我找到的分数值显示给 html 元素。
JavaScript 代码:
if (matches==8){
var totalscore = calcScore();
document.getElementById("score").innerHTML=totalscore;
}
单击提交按钮时,我想将 totalscore 的值保存在我的用户数据库中。所以我尝试了类似的东西:
$("#sendscore").on("click",function(){
gamescore= document.getElementById('score').innerHTML;
$.ajax({
type:'POST',
url: 'score-processor.php',
data:{
gamescore: gamescore,
}
})
});
php 代码:
<?php
session_start();
$db = mysqli_connect('localhost', 'root', '', 'registration');
if (isset($_POST['login_user'])) {
$username = mysqli_real_escape_string($db, $_POST['username']);
$password = mysqli_real_escape_string($db, $_POST['password_1']);
if (empty($username)) {
array_push($errors, "Username is required");
}
if (empty($password)) {
array_push($errors, "Password is required");
}
if (count($errors) == 0) {
$password = md5($password);
$query = "SELECT * FROM users WHERE username='$username' AND password='$password'";
$results = mysqli_query($db, $query);
if (mysqli_num_rows($results) == 1) {
$_SESSION['username'] = $username;
header('location: profile.php');
}
else {
array_push($errors, "Wrong username/password combination");
}
}
}
if(isset($_POST['gamescore'])){
$fetch = "SELECT id FROM users WHERE username='$username'";
$fetchid =mysqli_query($db, $fetch);
while ($row=mysqli_fetch_array($fetchid)){
$id = $row['id'];
$gamescore= $_POST['gamescore'];
$updatescore= "INSERT INTO users(id, score)VALUES('$id','$gamescore') ON DUPLICATE KEY UPDATE score='$gamescore'";
mysqli_query($db, $updatescore);
}
}
在我的 html 中:
<?php session_start();?>
<body>
<p>Your score: <span id=score></p>
<button id="sendscore" class="Go-on">Submit</button>
数据库表有列、id、username、email、password 和 score。
在登录/注册期间收集id、用户名、电子邮件和密码列的值。
游戏运行流畅并显示分数,但是当我单击提交按钮时,单击该按钮应将值添加到表中,但没有任何反应,日志中没有错误,并且值未添加到表中。
【问题讨论】:
-
危险:你很容易受到SQL injection attacks的影响,你需要defend你自己。
-
发布数据应该存储在 ajax 选项的 data 属性中。它没有 gamecore 属性。
-
修复 Sql 注入漏洞后...您尚未在更新脚本中的任何地方定义 $id 和 $username 变量。查询将因此失败
-
请参考这篇解决AJAX调用stackoverflow.com/questions/8567114/…的其他帖子
-
请参阅stackoverflow.com/questions/60174/…,了解有关如何防止 SQL 注入攻击的更多信息。
标签: javascript html mysql ajax