Passing a JSON file to a php server and then save the data from it into a Mysql DB

Dimitris Markantonatos :

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.

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. 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.

Here is my javascript code :

$(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
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.

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 .

Barmar :

$_FILES['uploadingfile'] is an array with several pieces of information about the uploaded file. 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.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=372512&siteId=1