首页 > 解决方案 > ajax POST 到带有 SQL 的 PHP 页面

问题描述

我正在努力创建一个基于 Web 的评分应用程序。我希望我的成绩簿在用户输入数据时将分数更新到 SQL 数据库中,而不是依赖用户点击“保存”按钮。这是我第一次这样做,所以我有一些问题。

  1. 目前,此代码不会更新 SQL 表。我在这里做错了什么?

  2. 当 SQL 查询不成功时,如何添加错误处理程序?alert()如果 POST 失败和/或 SQL 语句未成功执行,我希望发生某种类型的事情。我将如何添加这个?

  3. 有没有更安全的方法来做我想做的事情?

期望的最终结果:

用户只需在输入字段中输入分数即可更新成绩簿,无需单击保存按钮。如果发生错误导致 SQL 表无法根据用户输入进行更新,则alert应该发生 javascript。

HTML/javascript 页面:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>


<input type='text' data-assID='6' data-usid='1' data-curScore='10' value='10'>


<script>
  $("input[type=text]").change(function(){
    var newScore = $(this).val();
    var curScore = $(this).attr('data-curScore');
    var assID = $(this).attr('data-assID');
    var usid = $(this).attr('data-usid');
    if (Number.isInteger(+newScore) || newScore == 'X' || newScore == 'x') {
      $.ajax({
        url: "SQL.php?assID=" + assID + "&usid=" + usid + "&score=" + newScore,
        type: 'POST'
      });
      alert('Successfully scored assignment '+assID+' to '+newScore+' for user '+usid+'!');
    } else {
      $(this).val(curScore);
      alert('The only valid input options are either an integer or \'X\'');
    }

  });
</script>

SQL.php页面源码:

<?php

  session_start();
  require '../dbh.int.php';


  if (isset($_POST)) {

    $usid = $_POST['usid'];
    $assID = $_POST['assID'];
    $score = $_POST['score'];

    if (is_numeric($score)) { // If the score is an integer
      if ($score == 0) {
        $SQL = mysqli_prepare($connection, "UPDATE assignGrades SET status = NULL, graded=?, score=0, submitted = NULL WHERE (usid=? AND assID=?)");
        mysqli_stmt_bind_param($SQL, "sss", date('Y-m-d H:i:s'), $usid, $assID);
      }
      else {
        $SQL = mysqli_prepare($connection, "UPDATE assignGrades SET status = NULL, graded=?, score=? WHERE (usid=? AND assID=?)");
        mysqli_stmt_bind_param($SQL, "ssss", date('Y-m-d H:i:s'), $score, $usid, $assID);
      }
      mysqli_stmt_execute($SQL); unset($SQL);
    }

  }


 ?>

SQL数据库结构: 在此处输入图像描述

标签: phpjqueryajax

解决方案


推荐阅读