将实时json数据插入mysql表

6qqygrtg  于 2021-06-18  发布在  Mysql
关注(0)|答案(0)|浏览(156)

打开了一个websocket隧道,我可以在console.log上看到json数据,现在我想把数据流保存在本地,基本上保存在一个mysql数据库中。我使用ajax和php来编写应用程序。
javascript代码:

stomp.connect(headers, function(cb) {
        //Subscribe to a 3rd party 
        var topic = stomp.subscribe('/destination', function(e) {

            var mes = e;
            var body = JSON.parse(e.body);

            //Insert Data to mySQL
            function jsRecordInsertWrite(){

                var jsObject = {
                    "Time": document.body.timestamp.value,
                    "SourceId": document.body.sourceId.value,
                    "TrackingId": document.body.trackingId.value
                };

                // ... the AJAX request is successful
                var updatePage = function (response) {
                    alert("insert record successful");
                };
                // ... the AJAX request fail
                var printError = function (req, status, err) {
                    alert("insert record failed");
                };

                // Create an object to describe the AJAX request
                $.ajax({
                    url        : 'send.php',
                    dataType   : 'json',
                    contentType: 'application/json', 
                    data       : jsObject,
                    type       : 'POST',
                    success: updatePage,
                    error: printError
                });
            }

        }, headers);
    });

php脚本:

<?php

//Creating a connection
$link = mysql_connect('localhost', 'root', '','test');\

//read the json file contents
$id =  $_GET['id'];
$timestamp =  $_POST['Time'];
$sourceId =  $_POST['SourceId'];
$trackingId =  $_POST['TrackingId'];

//insert into mysql table
$sql = "INSERT INTO tbl_Data(id, Time, SourceId, TrackingId)   
VALUES(NULL,'$timestamp', '$sourceId', $trackingId')";

if(!mysql_query($sql)) {
    die('Error : ' . mysql_error());
}

//database connection close
mysql_close($link);

?>

暂无答案!

目前还没有任何答案,快来回答吧!

相关问题