Insert multiple rows and documents from JSON files to MySQL database with PHP -
i wrote php code extract values json file , insert them mysql database.
<?php //connect mysql db $con = mysqli_connect("localhost","root","","db_tweets") or die('could not connect: ' . mysql_error()); //read json file contents $jsondata = file_get_contents('prova.json'); //convert json object php associative array $data = json_decode($jsondata, true); foreach ($data $u => $z){ foreach ($z $n => $line){ //get tweet details $text = $line['text']; $id_tweet = $line['id_str']; $date = $line['created_at']; $id_user = $line['user']['id_str']; $screen_name = $line['user']['screen_name']; $name = $line['user']['name']; $sqlu = "insert user(id_user, screen_name, name) values ('".$id_user."', '".$screen_name."', '".$name."')"; } } if(!mysqli_query($con, $sqlu)) { die('error : ' . mysql_error()); } ?>
in doing insert values in first line of table, overwriting previous value. remains last.
how can i:
1) insert values in multiple lines?
2) parse multiple json files?
with every loop you're overwriting last $sqlu
value before ever passing variable mysqli_query
function after loops. once loops completed you're left last assigned value $sqlu
, , that's 1 gets executed.
instead, execute query inside loop and...
use php mysqli_
functions mysqli_prepare
, mysqli_stmt_bind_param
, , mysqli_stmt_execute
simplify , secure query:
//connect mysql db $con = mysqli_connect("localhost","root","","db_tweets") or die('could not connect: ' . mysql_error()); // prepare insert query $stmt = mysqli_prepare($con, 'insert user(id_user, screen_name, name) values (?, ?, ?)'); // bind upcoming variable names query statement mysqli_stmt_bind_param($stmt, 'iss', $id_user, $screen_name, $name); // loop on json files $jsonfiles = array('prova.json', 'provb.json', 'provc.json'); foreach ( $jsonfiles $jsonfile ) { //read json file contents $jsondata = file_get_contents($jsonfile); //convert json object php associative array $data = json_decode($jsondata, true); foreach ($data $u => $z){ foreach ($z $n => $line){ //get tweet details $id_user = $line['user']['id_str']; $screen_name = $line['user']['screen_name']; $name = $line['user']['name']; // execute insertion mysqli_stmt_execute($stmt); } } }
so, not uses fewer database resources preparing query once, , has cleaner code, escapes insertion values protect against sql injection.
added array $jsonfiles
containing number of json filenames, , used foreach
construct loop on json files.
Comments
Post a Comment