Insert JSON data MySQL

Home > Json Tutorial > Insert JSON data MySQL

Best PHP Live Project Based Winter Training in Noida for more details click here



Create Database and Table

//create  database
CREATE DATABASE demo;
 
USE demo;
 
//create  table JSON
CREATE TABLE json(
id INT NOT NULL AUTO_INCREMENT PRIMARY KEY ,
firstName CHAR( 50 ) NOT NULL ,
lastName CHAR( 50 ) NOT NULL

Create a JSON file

{"FirstName":"ravi", "LastName":"srivastva"}

PHP Script read JSON file contents and Insert into MySQL

<?php
$host="localhost";
$user="root";
$pass="";
$db="demo";
$connect= new mysqli($host,$user,$pass,$db) or die("ERROR:could not connect to the database!!!");

$fo=fopen("json_file.json","r");
$fr=fread($fo,filesize("json_file.json"));
$array=json_decode($fr,true);

//To display all values from JSON file
//print_r($array);
 
$query="insert into json values('','$array[FirstName]','$array[LastName]')";

$connect->query($query);

echo "Data Imported Sucessfully from JSON!";
?>