将字符串通过jQuery AJAX传递给PHP

时间:2018-03-22 11:38:28

标签: php jquery ajax

我有一个AJAX代码,可以将ID发布到PHP页面,一年和一个学期,以及成功函数。我控制数据以查看JSON数组,但是当我没有将学期放入PHP的AND子句时,它只显示JSON数组。我的代码:

AJAX:

$(document).ready(function() {
    $("#semester").change(function() {
        $("#year").change(function() {
            $('.searchBtn').click(function() {
                var id = this.id;
                var year = $("#year option:selected").val();
                var semester = $("#semester option:selected").val();

                console.log(id);
                console.log(semester);
                console.log(year);

                $.ajax({
                    traditional:true,
                    url: "getLoad.php",
                    method: "POST",
                    data:{
                        id:id,
                        semester:semester,
                        year:year
                    },
                    dataType: "JSON",
                    success:function(data){
                        console.log(data);
                        $("#studentLoad").css("display","block");
                       // $("#courseCode").text(data.sem);
                    }
                });
            });
        });
    });
});

PHP:

<?php
require("connect.php");
$query = "SELECT * FROM stud_enrollment AS se JOIN subjectschedule AS s ON se.subjectscheduleid = s.subSchedID JOIN subject AS sub ON sub.subjectID = s.subjectid WHERE se.studentid = {$_POST['id']} AND s.academic_year_start = {$_POST['year']} AND s.semester = {$_POST['semester']}";
$retval = mysqli_query($db, $query);
$data = array();
while($row = mysqli_fetch_assoc($retval)) {
    $data[] = $row;
}
echo json_encode($data);
?>

从AND子句中删除学期将允许数据出现在控制台中,但添加它将反过来。

1 个答案:

答案 0 :(得分:0)

正如每个人都说你应该准备好你的查询,你很容易成为MYSQL注射的受害者。

看看:

http://php.net/manual/en/mysqli.prepare.php

https://www.w3schools.com/sql/sql_injection.asp

代码似乎很好,你确定你的数据集是正确的吗? 我的意思是,你检查过是否存在满足该标准的行?

我按照以下方式重新编写您的查询:

$query = "SELECT * FROM stud_enrollment AS se JOIN subjectschedule AS s ON se.subjectscheduleid = s.subSchedID JOIN subject AS sub ON sub.subjectID = s.subjectid WHERE se.studentid = ? AND s.academic_year_start = ? AND s.semester = ?";


$mysqli = new mysqli("localhost", "my_user", "my_password", "world");

$stmt = $mysqli->prepare($query);

/* bind parameters */
$stmt->bind_param("i", $_POST['id']);
$stmt->bind_param("i", $_POST['year']);
$stmt->bind_param("s", $_POST['semester']);

/*execute the query*/
$stmt->execute();

// Extract result set and loop rows
$result = $stmt->get_result();
while ($res = $result->fetch_assoc())
{
    $data[] = $res;
}

/* close statement */
$stmt->close();

echo json_encode($data);