JSON stands for JavaScript Object Notation and it is widely used in exchanging data between the server and the client. It is text-based and lightweight. PHP has some built-in functions to handle JSON data.
In this tutorial, we will use a sample JSON file and insert the data from the JSON file into a MySQL table. We will use the PHP function json_decode() to get the data from the JSON file to an associative array.
Create a sample JSON file
We will use a sample JSON file for our tutorial. This file contains the user details with fields as name, age, gender and subject. We will use the below file for our learning:
[
{"name":"John","age":30,"gender":"Male","subject":"PHP"},
{"name":"Robert","age":35,"gender":"Male","subject":"Java"},
{"name":"Sherry","age":30,"gender":"Female","subject":"C#"},
{"name":"Peter","age":40,"gender":"Male","subject":"Python"},
{"name":"","age":40,"gender":"Male","subject":"Python"},
{"name":"Sundar","age":40,"gender":"","subject":"Python"}
]
Note the format of the JSON file data, it uses key:value pairs and is written within '{}'. The entire dataset is within '[]'. Let's name this file as "jason_data.json" and save this file in the same project folder. We will use a folder named "load_json" under "xampp/htdocs".
Create a MySQL table to store data from the JSON file
We will create a table named 'users' in a MySQL database. We will be using the "test" database. The table structure is given below:
The table 'users' has 5 columns in it.
- id - it is the primary key and auto-incremented
- name - name of the user
- age - age of the user
- gender - gender of the user
- subject - The subject the user is assigned to.
You can use the below SQL script to create the table.
CREATE TABLE `users` (
`id` int(11) NOT NULL,
`name` varchar(255) NOT NULL,
`age` tinyint(4) NOT NULL,
`gender` varchar(30) NOT NULL,
`subject` varchar(255) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1 COLLATE=latin1_swedish_ci;
ALTER TABLE `users`
ADD PRIMARY KEY (`id`);
ALTER TABLE `users`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=1;
Write a PHP program to read the JSON file and insert the data into a MySQL table (load_json.php)
Now, we will write a PHP program to read this JSON file and insert the data in the "users" table we created above.
<?php
// Connect to database
$conn = new mysqli("localhost","root","","test");
if ($conn->connect_error){
die("Database connection failed");
}
$filename = "jason_data.json";
$counter = 0;
$json_data = file_get_contents($filename);
$data_arr = json_decode($json_data,true);
$sql = "insert into users (name,age,gender,subject) values(?,?,?,?)";
$stmt = $conn->prepare($sql);
$stmt->bind_param("siss", $name, $age, $gender, $subject);
foreach($data_arr as $row){
$name = $row['name'];
$age = $row['age'];
$gender = $row['gender'];
$subject = $row['subject'];
if (!empty($name) && !empty($age) && !empty($gender) && !empty($subject)){
$stmt->execute();
$counter++;
}
}
if ($counter == count($data_arr)){
echo $counter." Rows inserted successfully";
}
else{
$failed_rows = count($data_arr) - $counter;
echo nl2br($counter . " Rows inserted successfully\n");
echo $failed_rows." Rows are not inserted because of error";
}
- We are using
mysqli_connect() function with four parameters. For a successful connection, $conn will be true.
- Then, we assign the filename for our JSON data. Also, initialize a counter, which will give the number of rows that will be inserted in the database.
- Then in lines 11 and line 12, we get the content of the file in a string variable and then convert the JSON data into an associative array.
json_decode() function does this. Use the second parameter as true for an associative array. If you give the second parameter in this function as false or omit this parameter, it will return a PHP object.
- Then we write the SQL insert statement using the prepare() method. So, instead of directly putting the values in the SQL statement we use placeholders. Use bind_param() to associate the values with the placeholders.
- Then using a loop we go through the associative array and execute the statement. Before executing, check for non-empty values.
- After the LOOP is finished, display the number of rows successfully inserted and also the number of rows which are not inserted due to error.
Test the Application
Make sure Apache and MySQL services are running in your XAMPP control panel. Run localhost/load_json.php in the browser. You will see that some rows are successfully inserted, but some of the rows not inseretd because of an error. If you check the json file, you will see that the last two rows are having issues because the fields are missing values. So, when we ran this program we got the below output:
Now check the database table, you will see 4 rows are inserted and the last 2 rows are not inserted due to empty field values.
Conclusion
In this tutorial, we have developed an application in PHP and MySQL to read a JSON file and insert the data into a MYSQL table. I hope it will be useful to you while working in your project with JSON data.
Please write your comments/questions in the Comments section below. Your questions, doubts and suggestions are always welcome.
Post a Comment