我正在创建一个提问题的测验页面,最后会显示最高分数表。我通过Ajax访问此页面以插入用户名和分数,并将其插入两次。
<?php
$servername = "localhost";
$username = "root";
$password = "pswd";
$dbname = "mydb";
$toJsonArr = array();
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
if (isset($_GET["username"])) {
$username = $_GET["username"];
$score = $_GET["score"];
$sql = "INSERT INTO `fullstackQuiz` (`id`, `place`, `username`, `points`, `now`) VALUES (NULL, '0', '$username', '$score', CURRENT_TIMESTAMP);";
$result = $conn->query($sql);
if ($conn->query($sql) === TRUE) {
echo "1";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
} else {
$sql = "SELECT * FROM `fullstackQuiz` ORDER BY `fullstackQuiz`.`points` DESC LIMIT 10";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
$toJsonArr[] = $row;
}
} else {
echo "0 results";
}
echo json_encode($toJsonArr);
$conn->close();
}
?>
我的Ajax代码:
$.ajax({
type: "GET",
url: "sql.php",
data: { username: "abc", score: "99" },
success: function(data) {
console.log("success");
}
});
每次Ajax运行时,它都会因某种原因创建两次记录。
你重复了两次$conn->query($sql)
。删除一个,它将工作:
//$result = $conn->query($sql); <== Remove this line.
if ($conn->query($sql) === true) {
echo "1";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
也不要将NULL
传递给自动增量ID,只需将其从查询中排除即可。如果place
字段是数字,则将值作为数字传递而不带撇号:
$sql = "INSERT INTO `fullstackQuiz` (`place`, `username`, `points`, `now`)
VALUES (0, '$username', '$score', CURRENT_TIMESTAMP);";
最后,您的查询对SQL攻击开放。请改用参数化查询。