[英]Passing a JSON file to a php server and then save the data from it into a Mysql DB
As the tittle says i'm coding a web app as part of a school project.正如标题所说,我正在编写一个网络应用程序作为学校项目的一部分。 My goal is for someone to upload a json file and save some data of it in a table on Mysql for further functionallity in the app.我的目标是让某人上传一个 json 文件并将它的一些数据保存在 Mysql 的表中,以便在应用程序中进一步发挥作用。
My question is how exaclty can you pass a JSON file to PHP and then parse it from there as to store the wanted data to the DB.我的问题是如何精确地将 JSON 文件传递给 PHP,然后从那里解析它以将所需的数据存储到数据库。 I tried sending it with the help of Jquery fileupload as the json files may be quite large and on the php side i used the function file_get_contents but i had no luck with it.我尝试在 Jquery fileupload 的帮助下发送它,因为 json 文件可能非常大,在 php 端我使用了函数file_get_contents但我没有运气。
Here is my javascript code :这是我的 javascript 代码:
$(document).ready(function () {
$("#submitupload").click(function(){
var files = $("#files");
$("#uploadedfile").fileupload({
url: 'upload.php',
dataType: 'json',
autoUpload: false
}).on('fileuploadadd', function (e, data) {
var fileTypeAllowed = /.\.(json)$/i;
var fileName = data.originalFiles[0]['name'];
var fileSize = data.originalFiles[0]['size'];
console.log(data);
if (!fileTypeAllowed.test(fileName)){
$("#error").html('Only json files are allowed');
}else
data.submit();
}).on('fileuploaddone', function (e , data){
var msg = data.jqXHR.responseJSON.msg;
$("#error").html(msg);
}).on('fileuploadprogress', function (e,data){
var progress = parseInt(data.loaded / data.total * 100, 10 );
$("#progress").html("Completed: " + progress + "%");
})
})
})
And here is the PHP :这是 PHP :
<?php
include_once ('connection.php');
if (isset($_FILES['uploadingfile'])){
$file = $_FILES['uploadingfile'];
$data = file_get_contents($file);
$array = json_decode($data, true );
foreach( $array as $row){
$sql = "INSERT INTO locations(timestamp) VALUES ('".$row["timestampMs"]."')";
mysqli_query($conn, $sql);
}
$msg = array("msg" => "times ok ");
exit(json_encode($msg));
}
Noticed the error in file_get_contents() that says that the $file variable is an array not a string so i tried to pass the $_FILES variable as an argument with no luck again.注意到file_get_contents()中的错误表明$file变量是一个数组而不是一个字符串,所以我试图将 $_FILES 变量作为参数传递,但再次没有运气。
Is this the correct way to way to do it and if yes what am i missing or should i use another approach?这是正确的方法吗?如果是的话,我缺少什么还是应该使用另一种方法?
Thanks for the long read and your time in advance !感谢您的长期阅读和您提前的时间! Sorry if any of this sounds stupid but im new to PHP .对不起,如果这听起来很愚蠢,但我是 PHP 新手。
$_FILES['uploadingfile']
is an array with several pieces of information about the uploaded file. $_FILES['uploadingfile']
是一个包含有关上传文件的几条信息的数组。 So you need to use:所以你需要使用:
$file = $_FILES['uploadingfile']['tmp_name'];
to get the filename where the data is stored.获取存储数据的文件名。
See Handling File Uploads for full details.有关完整详细信息,请参阅处理文件上传。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.