必承其重 | 欲带皇冠 2018-02-03 15:15 采纳率: 0%
浏览 56

SQL查询插入两次

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.

  • 写回答

1条回答 默认 最新

  • 叼花硬汉 2018-02-03 15:21
    关注

    You repeated $conn->query($sql) twice. Remove one and it will work:

    //$result = $conn->query($sql); <== Remove this line.
    
    if ($conn->query($sql) === true) {
        echo "1";
    } else {
        echo "Error: " . $sql . "<br>" . $conn->error;
    }
    

    Also don't pass NULL to an auto-increment ID, just exclude it from the query. And if the place field is a number, then pass the value as a number without apostrophes:

    $sql = "INSERT INTO `fullstackQuiz` (`place`, `username`, `points`, `now`)
            VALUES (0, '$username', '$score', CURRENT_TIMESTAMP);";
    

    Finally, your query is open to SQL attacks. Use a parameterized query instead.

    评论

报告相同问题?

悬赏问题

  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥16 mybatis的代理对象无法通过@Autowired装填
  • ¥15 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂
  • ¥15 wordpress 产品图片 GIF 没法显示
  • ¥15 求三国群英传pl国战时间的修改方法
  • ¥15 matlab代码代写,需写出详细代码,代价私
  • ¥15 ROS系统搭建请教(跨境电商用途)
  • ¥15 AIC3204的示例代码有吗,想用AIC3204测量血氧,找不到相关的代码。