使用JSON,XMLHttpRequest和PHP file_get_contents(" php:// input")填充数据库的简单示例

时间:2018-01-14 01:15:01

标签: php mysql json

现在我知道以前曾经问过这个问题,但迄今为止没有一个回复为我提供了见解;

我有一个带有下面脚本的HTML页面(最终我将使用此脚本从应用程序中吸取数据),基本上测试将一些JSON格式的数据发送到PHP页面,该页面用MYSQL数据库填充记录。

我的问题是我没有更新表记录。纳达。

这已经让我搞乱了几个星期了;我最接近的是:

Send JSON data from Javascript to PHP?

我迄今为止取得的有限成功是从.json文件中获取数据并在php页面上以这种方式更新数据库。因此,JSON在脚本中很好,并且与数据库的连接是可以的。我似乎无法将它从html页面传递给php并填充数据库。我无法理解为什么会这么困难。

任何建议/指针都会受到赞赏(我需要保持这个简单,因为我是一个相对新手)。提前谢谢。

HTML页面脚本



    <script>
    var jsonQuizData = {};
    var qID = '9';
    var learnersName = 'Bart Bundy';
    var learnersEmail = 'bbundy@blue.com';
    var quizName = 'SomeQuiz99';
    var quizScore = '33%';
    var result1 = 'Some blob data goes in here?';
    var dbString, request;	
	
    jsonQuizData = '{ "id":qID, usersName":learnersName,  "usersEmail":learnersEmail,  "quizTitle":quizName, "qScore":quizScore, "Output1":result1 }';

    dbString = JSON.stringify(jsonQuizData);

    request = new XMLHttpRequest();
    request.open("POST", "process.php", true);
    request.setRequestHeader("Content-Type", "application/json"); 
    request.send(dbString);
    </script>
&#13;
&#13;
&#13;

process.PHP页面

&#13;
&#13;
<?php
    header("Content-Type: application/json; charset=UTF-8");

    //Create connection
    $conn = mysqli_connect($servername, $username, $password, $dbname);
    // Check connection etc. performed here

    $data = json_decode(file_get_contents("php://input"));

    $id = $data['id'];
    $name = $data['usersName'];
    $email = $data['usersEmail'];
    $qtitle = $data['quizTitle'];
    $result1 = $data['Output1'];
    $qScore = $data['score'];

    //insert into mysql table
    $sql = "INSERT INTO quiz01(quiz_id, quiz_title, fName, eMail, quiz_score, q1_answer)
    VALUES('$id', '$qtitle', '$name', '$email', '$qScore', '$result1')";

    if(!mysqli_query($conn,$sql))
    {
    die('Error : ' . mysqli_error($conn));
    }
    else
	{
	echo "Data inserted successfully";
	}

    //Close connection
    /?>
&#13;
&#13;
&#13;

....砖墙时间

2 个答案:

答案 0 :(得分:0)

你的样本中的stringify部分不正确,它已经是一个字符串,所以我认为你的意思是:

var jsonQuizData = {};
var qID = '9';
var learnersName = 'Bart Bundy';
var learnersEmail = 'bbundy@blue.com';
var quizName = 'SomeQuiz99';
var quizScore = '33%';
var result1 = 'Some blob data goes in here?';
var dbString, request;
// Here you have to stringify the data object, not a string of the data object.
jsonQuizData = JSON.stringify({"id":qID, "usersName":learnersName, "usersEmail":learnersEmail,  "quizTitle":quizName, "qScore":quizScore, "Output1":result1});

request = new XMLHttpRequest();
request.open("POST", "process.php", true);
// Send the regular form header
request.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
request.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
        alert(this.responseText);
    }
};
// Now when it sends, it should send it properly as a post
request.send('json='+jsonQuizData);

然后在PHP中,您不需要发送该行:

header("Content-Type: application/json; charset=UTF-8");

你可以改变这一行:

$data = json_decode(file_get_contents("php://input"));

只是:

$data = json_decode($_POST['json'],true);

它现在应该都是常规的$_POST,然后你需要在插入时绑定参数。

答案 1 :(得分:0)

更新: 是的,让它按照以下方式工作:

HTML页面

<script>
var jsonQuizData = {};
var learnersName = 'Professor T';
var learnersEmail = 'prof.teerlink@pooh.com';
var quizName = 'TidlyWinks101w';
var quizScore = '100%';
var result1 = 'Balls said the crow';
var dbString, request;  

jsonQuizData = JSON.stringify({"quizTitle":quizName, "usersName":learnersName, "usersEmail":learnersEmail, "qScore":quizScore, "Output1":result1 });

$(document).ready(function()
{
$("button").click(function()
    {
    $.post("working01.php", 'json='+jsonQuizData, 
    function(data,status)
        {
        //alert("Data: " + data + "\nStatus: " + status);
        document.getElementById("AV1").innerHTML = data;
        });
    });
});
</script>

PHP页面......

<?php
//Set up connections to database etc...

if (isset($_POST['json'])) 
{
$str = $_POST['json'];
$contents = json_decode($str);
$qtitle = $contents->quizTitle;
$name = $contents->usersName;
$email = $contents->usersEmail;
$qScore = $contents->qScore;
$result1 = $contents->Output1;
}
$sql = "INSERT INTO quiz01(quiz_title, fName, eMail, quiz_score, q1_answer)
VALUES('$qtitle', '$name', '$email', '$qScore', '$result1')";

if(!mysqli_query($conn,$sql))
{
    die('Error : ' . mysqli_error($conn));
}
else
{
    echo "Data inserted successfully";
}

//Close connections
?>

但是想要利用XMLHttpRequest()对象并发送json。 按照拉斯克拉特的说法。感谢