I created the JSon file using the c# to export the selected records from the local MySQL database. The php code is used to insert the JSon file recods to the MySQL remote database. But the problem is, when I run the php code, it only inserts the first record from the JSon to the database rather than all records in the JSon file.
But I want to insert all the records to the database.
table : tbl_sales
the id field is AutoIncrement
+--------------------+-------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+--------------------+-------------+------+-----+---------+----------------+
| sale_item | varchar(20) | NO | | NULL | |
| sale_qty | int(11) | NO | | NULL | |
| local_row_added_on | datetime | NO | | NULL | |
| last_edited_on | datetime | YES | | NULL | |
| id | int(11) | NO | PRI | NULL | auto_increment |
+--------------------+-------------+------+-----+---------+----------------+
<?php
$connect = mysqli_connect("localhost", "root", "", "mytest"); // 1.
$query = '';
$table_data = '';
$filename = "path.json";
$data = file_get_contents($filename); // 2.
$array = json_decode($data, true); // 3.
foreach($array as $row) // 4.
{
$query .= "INSERT INTO tbl_sales(sale_item, sale_qty, local_row_added_on, last_edited_on) VALUES ('".$row["sale_item"]."', '".$row["sale_qty"]."', '".$row["local_row_added_on"]."', '".$row["last_edited_on"]."'); "; // 5.
mysqli_query($connect, $query); // 6.
}
echo "<h1>Successfully Imported JSON Data</h1>";
// 1. Connect PHP to MySQL Database
// 2. Read the JSON file in PHP
// 3. Convert JSON String into PHP Array
// 4. Extract the Array Values by using Foreach Loop
// 5. Make Multiple Insert Query
// 6. Run Mutliple Insert Query
?>
JSon file records(path.json) :
[
{
"sale_item":"Sugar",
"sale_qty":"5",
"local_row_added_on":"2018-05-08 10:10:24",
"last_edited_on":"2018-05-08 10:10:24",
"id":"1"
},
{
"sale_item":"Keyboard",
"sale_qty":"2",
"local_row_added_on":"2018-05-07 08:14:41",
"last_edited_on":"2018-05-07 06:14:53",
"id":"2"
},
{
"sale_item":"Biscuit",
"sale_qty":"3",
"local_row_added_on":"2018-05-06 12:15:17",
"last_edited_on":"2018-05-06 12:15:35",
"id":"3"
},
{
"sale_item":"Pen",
"sale_qty":"25",
"local_row_added_on":"2018-05-14 03:20:22",
"last_edited_on":"2018-05-14 03:20:25",
"id":"4"
},
{
"sale_item":"Snacks",
"sale_qty":"6",
"local_row_added_on":"2018-05-07 05:30:40",
"last_edited_on":"2018-05-16 05:30:40",
"id":"5"}
]
$queryso it includes multiple queries.mysqli_query()only executes one query, so only the first is used. Instead of running the query on each iteration, you could build one multi-insert query:INSERT INTO table (col1, col2) VALUES (row1val1, row1val2), (row2val1, row2val2), ...and so on.mysqli_connecttomysqli_multi_connect.