I'm creating a quiz page that would ask questions and at the end will show top scores table. I'm accessing this page through Ajax to insert username and score and it's inserting it twice.
<?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();
}
?>
My Ajax code:
$.ajax({
type: "GET",
url: "sql.php",
data: { username: "abc", score: "99" },
success: function(data) {
console.log("success");
}
});
Every time the Ajax runs, it will create the record twice for some reason.