Tuesday 14 June 2016

Insert JSON Data Into MySQL Using PHP

The following is the JSON file which we have already created earlier.
[{
"sno": "1",
"name": "vikram",
"course": "php"
}, {
"sno": "2",
"name": "lucky",
"course": "java"
}, {
"sno": "3",
"name": "vikram",
"course": "php"
}, {
"sno": "4",
"name": "kkk",
"course": "java"
}, {
"sno": "5",
"name": "kkkkkk",
"course": "kk"

}]

PHP code to Insert JSON data into MySQL using PHP :

$string = file_get_contents("results.json");
$data = json_decode($string,true);
//print_r($data);
$con = mysqli_connect('localhost','root','','test');
//echo $data[0]['sno'];
foreach ($data as $key => $val)
{
       $sno = $val['sno'];
$name = $val['name'];
$course = $val['course'];
$sql = "insert into students2(sno,name,course) values('".$sno."','".$name."','".$course."')";
$result = mysqli_query($con,$sql);
if($result)
echo "Inserted";
else 
echo "Not Inserted";
}
?>

No comments:

Post a Comment