PHP没有使用正确的SQL语法将数据插入MySQL表

时间:2016-02-27 00:39:40

标签: javascript php jquery mysql

我试图通过PHP将通过jquery $ .ajax POST传递的JSON对象数组插入到MySQL数据库中。我似乎已经尝试了所有的东西,但由于某种原因,我无法让它发挥作用。任何建议都会非常感激。

PHP

<?php

$servername = "servername";
$username = "username";
$password = "password";
$dbname = "dbname";

$conn = new mysqli($servername, $username, $password, $dbname);

if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
} 

$data = json_decode($_POST, true);

foreach ($data as $item) {
    $worker_id = $item['worker_id'];
    $response_time = $item['time'];
    $video_id = $item['video_id'];
    $submission = $item['response'];
    $test_answer = $item['test_answer'];

    $sql = "INSERT INTO nristudy (worker_id, response_time, video_id, submission, test_answer) 
    VALUES ('$worker_id', '$response_time', '$video_id', '$submission', '$test_answer')";

    if (!($conn->query($sql))) {
        die($conn->error);
    }

}

if (!$conn->commit()) {
    echo "Transaction commit failed";
    exit();
}

$conn->close();
?>

的Javascript

var json = JSON.stringify(submissions);

$.ajax({
    type: "POST",
    url: "http://hci.cs.wisc.edu/nri/store_data.php",
    data: json,
    success: function(data){
        console.log("Success: " + data);
    },
    error: function(jqXHR, textStatus, errorThrown) {
        alert('An error occurred... look at the console for more information!');   
        console.log('jqXHR:');
        console.log(jqXHR);
        console.log('textStatus:');
        console.log(textStatus);
        console.log('errorThrown:');
        console.log(errorThrown);
    }
});

1 个答案:

答案 0 :(得分:0)

问题的解决方案在很大程度上取决于错误。但是,有一件事非常清楚,那就是你应该转义你想要放入查询的字符串。

我建议您切换到使用PDO和预处理语句,因为您不必担心转义任何内容,并且在准备语句时可以依赖PDO来处理它。

您可能还想尝试序列化而不是json_encode,但是如果它有效,那么SQL注入对您来说仍然是一个非常大的可能性。