How can i insert the json data into different mysql tables? - php

I have the json file like below, i want the states to be entered first in state table, and the corresponding name that is the city should enter in another table and should take the id of the concerned state as the state id there are more than 1700 data. the sql structure should be
States table
id state
Cities table
id city state_id
where state id refers to the id of the state so that i can use joins.
[
{
"id": "1",
"name": "Mumbai",
"state": "Maharashtra"
},
{
"id": "2",
"name": "Delhi",
"state": "Delhi"
},
{
"id": "3",
"name": "Bengaluru",
"state": "Karnataka"
},
{
"id": "4",
"name": "Ahmedabad",
"state": "Gujarat"
},
{
"id": "5",
"name": "Hyderabad",
"state": "Telangana"
}
]
i have converted the json file into an array
$json = file_get_contents("resources/statelist.json");
$array = json_decode($json, true);
how i can accomplish that? or any alternative as i am quite new to php..
note: there are many cities with same states the above json is just a part of full json.

Do the following
foreach($array as $row){
$query = "INSERT INTO Cities values('".$row['id']."','".$row['city']."','".$row['state']."' )" ;
$res = mysql_query($query);
}

Related

How do I add a document to existing filled collection?

I am building an eShop for educational purposes and I need to handle the orders from a user. A user has a basket which is getting filled with products. If he decides buy another product I have insert a document into the existing collection of the card
Current MongoDB collection:
{
"_id": {
"$oid": "61f3d79c921000006000547d"
},
"username": "mike",
"products": {[
"number": "3",
"name": "Honduras",
"price": 7,
"stock": 10,
]},
"status": "UNPAID"
}
By adding another product, needs to be inserted in the existing collection in the field of products.
Expected to look like:
{
"_id": {
"$oid": "61f3d79c921000006000547d"
},
"username": "mike",
"products": {[
"number": "3",
"name": "Honduras",
"price": 7,
"stock": 10,
], [
"number": "4",
"name": "India",
"price": 10,
"stock": 11,
]},
"status": "UNPAID"
}
I am using PHP for the back end operations. The script that I wrote it is simple. I am searching if orders with user's username exist. If they exist then I lock the current order and make the operations needed.
I think that I am missing something in syntax of the update for the purpose described above:
PHP script:
if (isset($_POST['add'])){
// Ordered by name from URL
$username = $_GET['username'];
// Product info
$name = $_POST['add'];
// Finds the product selected from products
$product = $collection -> findOne(array("name" => "$name"));
// Serialize product to be added.
$json = MongoDB\BSON\toJSON(MongoDB\BSON\fromPHP($product));
// Searching for order from certain user
$collection = $db -> orders;
$exists = $collection -> findOne(array("username" => "$username"));
if (!is_null($exists)){
// The problem is here (maybe?)
$exists->updateOne(
array("products" => {}),array('$set'=>$json);
);
}
Any help and suggestions would be really appreciated!
Well, you need to use something like below
db.collection.update(
{find Condition},
{$push: {products : {key: value, key2: value 2}}
)
Here the catch is push. It adds an element to array. Here the element is an object.

Foreach loop don't show fetch data from database correctly

I have two tables in the database (details and image) and I fetch the first table correctly(details).details has a row with name is code and I want to fetch the image table with the code element that comes in the details table.
the table details are like this :
$response = array();
$sql = " SELECT * FROM `details` ORDER BY `id` DESC ";
$run = $connect->prepare($sql);
$run->execute();
$record = $run->fetchAll(PDO::FETCH_ASSOC);
$response['res'] =[$record];
echo json_encode($response,JSON_PRETTY_PRINT);
and the response is like this:
{
"res": [
[
{
"id": "1",
"title": "bucher",
"name": "jack sib",
"start": "7am to 6pm",
"details": "gtgtty rtrtrt",
"user": "example#yahoo.com",
"code": "ulv1mx8wztcyvf55ns4hlcgr11lzktyh",
"time": "2020-08-21 16:24:19"
},
{
"id": "2",
"title": "super market",
"name": "alibaba",
"start": "6 Am to 6 Pm",
"details": "everything is good and get better",
"user": "example2#yahoo.com",
"code": "umtyw95hu4voe49rz95ej0cftmnglom1",
"time": "2020-08-17 17:26:40"
}
}
and everything is good and correct, but when i want to fetch image from database and i want to show every image with the special code but it just show me one image with the code.
i write code fething image like this:
foreach ($record as $row){
$sqlImage = " SELECT * FROM `image` WHERE code= ? LIMIT 1 ";
$runImage = $connect->prepare($sqlImage);
$runImage->bindValue(1, $row['code']);
$runImage->execute();
$recordImage = $runImage->fetchAll(PDO::FETCH_ASSOC);
}
and the response is :
{
"advert": [
[
{
"id": "1",
"title": "bucher",
"name": "jack sib",
"start": "7am to 6pm",
"details": "gtgtty rtrtrt",
"user": "example#yahoo.com",
"code": "ulv1mx8wztcyvf55ns4hlcgr11lzktyh",
"time": "2020-08-21 16:24:19"
},
{
"id": "2",
"title": "super market",
"name": "alibaba",
"start": "6 Am to 6 Pm",
"details": "everything is good and get better",
"user": "example2#yahoo.com",
"code": "umtyw95hu4voe49rz95ej0cftmnglom1",
"time": "2020-08-17 17:26:40"
}
],
[
{
"id": "1",
"user": "example2#yahoo.com",
"url": "..\/public\/uploadPic\/cb49f60092bb9b28e69487171208a0d09.jpg",
"token": "umtyw95hu4voe49rz95ej0cftmnglom1"
}
]
]
}
and the second image is not displayinag and i don't know why.
This will probably fetch the wanted results in a single query, including the image if exists for the specific code. Otherwise, it will return NULL in the image table columns.
SELECT details.*, image.* FROM details LEFT JOIN details
ON image.code = details.code ORDER BY details.id DESC
Please be aware that you're pulling out all data from image table, which seems unnecessary as you already have the code from the first table and only need the image URL and token.
You can rewrite the query to only append the image from the second table:
SELECT details.*, image.url, image.token FROM details LEFT JOIN details
ON image.code = details.code ORDER BY details.id DESC

Inserting records between JSON entries using PHP

I've got a nice simple bit of PHP which grabs data from my database View and makes a JSON file and then writes it to my server.
It's a list of employees from 5 different companies.
What I'd like to be able to do, is before the first employee of each company that gets returned is to insert an item which represents the company (inc a logo).
So, it would look something like this...
COMPANY 1
EMPLOYEE
EMPLOYEE
EMPLOYEE
COMPANY 2
EMPLOYEE
COMPANY 3
EMPLOYEE
EMPLOYEE
At the moment I'm just getting all the employees.
This is my PHP that generates the JSON
<?php
$db=new PDO('mysql:dbname=DB;host=localhost;','username','pass');
$row=$db->prepare('select * from Employee_JSON');
$row->execute();//execute the query
$json_data=array();//create the array
foreach($row as $rec)//foreach loop
{
$json_array['employee_id']=$rec['employee_id'];
$json_array['employee_firstname']=$rec['employee_firstname'];
$json_array['employee_surname']=$rec['employee_surname'];
$json_array['employee_image']=$rec['employee_image'];
$json_array['employee_status']=$rec['employee_status'];
$json_array['company_id']=$rec['company_id'];
$json_array['company_name']=$rec['company_name'];
$json_array['company_hex']=$rec['company_hex'];
//here pushing the values in to an array
array_push($json_data,$json_array);
}
//built in PHP function to encode the data in to JSON format
echo json_encode($json_data);
//write to json file
$fp = fopen('data/employees.json', 'w');
fwrite($fp, json_encode($json_data));
fclose($fp);
?>
Here is my JSON sample returned.
[{
"employee_id": "9",
"employee_firstname": "Test",
"employee_surname": "Name",
"employee_image": "9.jpg",
"employee_status": "1",
"company_id": "1",
"company_name": "CDE",
"company_hex": "99C440"
}, {
"employee_id": "49",
"employee_firstname": "Testy",
"employee_surname": "Test",
"employee_image": "ce_holding.png",
"employee_status": "1",
"company_id": "1",
"company_name": "CDE",
"company_hex": "99C440"
}, {
"employee_id": "8",
"employee_firstname": "Tester",
"employee_surname": "McTest",
"employee_image": "8.jpg",
"employee_status": "1",
"company_id": "1",
"company_name": "CDE",
"company_hex": "99C440"
}]
I have two tables in the database, a Company table that contains the URL of the image I want and an Employee table that has all the employee data.
Here is the Company table structure
Here is the Employee table structure
I then do an Inner Join on those to create my database View which is called in the PHP sample.
CREATE VIEW `Employee_JSON`
AS SELECT
`Employee`.`employee_id` AS `employee_id`,
`Employee`.`employee_firstname` AS `employee_firstname`,
`Employee`.`employee_surname` AS `employee_surname`,
`Employee`.`employee_image` AS `employee_image`,
`Employee`.`employee_status` AS `employee_status`,
`Company`.`company_id` AS `company_id`,
`Company`.`company_name` AS `company_name`,
`Company`.`company_hex` AS `company_hex`
FROM (`Employee` join `Company` on((`Employee`.`employee_company_id` = `Company`.`company_id`))) where (`Employee`.`employee_active` = 1) order by `Company`.`company_name`,`Employee`.`employee_surname`,`Employee`.`employee_firstname`;
So my expected output could look something like this, where adding a "is_company": "1" into the JSON could help my app detect whether to display the company image or employee image.
[{
"employee_id": "0",
"employee_firstname": "Company",
"employee_surname": "Name",
"employee_image": "companyimage.jpg",
"employee_status": "1",
"company_id": "1",
"company_name": "CDE",
"is_company": "1",
"company_hex": "99C440",
}, {
"employee_id": "9",
"employee_firstname": "Test",
"employee_surname": "Name",
"employee_image": "9.jpg",
"employee_status": "1",
"company_id": "1",
"company_name": "CDE",
"company_hex": "99C440"
}, {
"employee_id": "49",
"employee_firstname": "Testy",
"employee_surname": "Test",
"employee_image": "ce_holding.png",
"employee_status": "1",
"company_id": "1",
"company_name": "CDE",
"company_hex": "99C440"
}, {
"employee_id": "8",
"employee_firstname": "Tester",
"employee_surname": "McTest",
"employee_image": "8.jpg",
"employee_status": "1",
"company_id": "1",
"company_name": "CDE",
"company_hex": "99C440"
}]
I'm then reading this JSON file into an iOS app to display the contents.
Any ideas how I might be able to achieve adding in those extra nodes?
Many thanks
Simon
Something like this might do the trick:
<?php
//Before this you should have the data you want to insert in the JSON of each company. I guess you should get it from a database.
$json_data_c=array();
foreach($row as $rec_company){ //I supose you have the information in the $row variable after a query to the database
$json_array['company_field1']=$rec_company['company_field1'];
....
$json_data_c[$rec_company['company_id']]=$json_array;
}
//end of company information
$db=new PDO('mysql:dbname=DB;host=localhost;','username','pass');
$row=$db->prepare('select * from Employee_JSON');
$row->execute();//execute the query
$json_data=array();//create the array
$company_id_loop=-1;
foreach($row as $rec)//foreach loop
{
if($company_id_loop!=$rec['company_id']){
//insert here the json with the data of the company $rec['company_id']
$json_array_company=$json_data_c[$rec['company_id']];
array_push($json_data, $json_array_company);
$company_id_loop=$rec['company_id'];
}
$json_array['employee_id']=$rec['employee_id'];
$json_array['employee_firstname']=$rec['employee_firstname'];
$json_array['employee_surname']=$rec['employee_surname'];
$json_array['employee_image']=$rec['employee_image'];
$json_array['employee_status']=$rec['employee_status'];
$json_array['company_id']=$rec['company_id'];
$json_array['company_name']=$rec['company_name'];
$json_array['company_hex']=$rec['company_hex'];
//here pushing the values in to an array
array_push($json_data,$json_array);
}
//built in PHP function to encode the data in to JSON format
echo json_encode($json_data);
//write to json file
$fp = fopen('data/employees.json', 'w');
fwrite($fp, json_encode($json_data));
fclose($fp);
?>

"Nested" array within db response using Codeigniter

I am trying to create a "nested" array within an object that I am returning from a database.
I can have more than one footnote per "thing".
This is what I am currently getting back:
JSON
{
"data": [{
"id": "123",
"type": "foo",
"color": "bar",
"footnote_id": "1",
"footnote_text": " Footnote one"
}]
}
Here is the result I'm trying to generate:
JSON
{
"data": [{
"id": "123",
"type": "foo",
"color": "bar",
"footnotes": [{
"footnote_id": "1",
"footnote_text": " Footnote one"
},
{
"footnote_id": "2",
"footnote_text": "Footnote two"
}]
}]
}
I have a footnotes table that has all kinds of footnotes (footnote_id and such).
I have a type table that has all kinds of things in it (type_id and such).
I also have a type_footnotes table that only has two columns: type_id and footnote_id
I'm not sure how to create the footnotes property of the response object - then display the results within that array.
Thank you for your time!
EDIT
Here is the query - I thought I had posted this as well. My apologies.
PHP
public function get_thing($type_id) {
$this->db->select('type.type_id, type.type, type.type_color');
$this->db->join('footnotes', 'footnotes.footnote_id, footnotes.footnote_text');
$this->db->join('type_footnotes, type_footnotes.type_id = type.type_id');
$query = $this->db->get_where('type', array('type.type_id' => $type_id), 1);
if ($query->num_rows() > 0) {
return $query->result();
}
}
Remove the limit, and post here what do you get as result :
$query = $this->db->get_where('type', array('type.type_id' => $type_id));

Json Traverse Problem, not able to traverse values

I m getting the below return from ajax call but not able to traverse it please please help.
{
"1": {
"tel1": null,
"status": "1",
"fax": "",
"tel2": null,
"name": "sh_sup1",
"country": "Anguilla",
"creation_time": "2010-06-02 14:09:40",
"created_by": "0",
"Id": "85",
"fk_location_id": "3893",
"address": "Noida",
"email": "sh_sup1#shell.com",
"website_url": "http://www.noida.in",
"srk_main_id": "0"
},
"0": {
"tel1": "Ahemdabad",
"status": "1",
"fax": "",
"tel2": "Gujrat",
"name": "Bharat Petro",
"country": "India",
"creation_time": "2010-05-31 15:36:53",
"created_by": "0",
"Id": "82",
"fk_location_id": "3874",
"address": "THIS is test address",
"email": "bp#india.com",
"website_url": "http://www.bp.com",
"srk_main_id": "0"
},
"count": 2
}
You can do it very easily:
for(i = 0; i < msg.count; i++) {
alert(msg[i]['name']);
}
But the structure of your JSON object is not that good for several reasons:
It does not reflect the structure of the actual data
With this I mean, that you actually have an array of objects. But in your JSON object the elements of the array are represented as properties of an object.
You have invalid JavaScript object property names.
Properties for objects in JavaScript are not allowed to start with numbers. But with msg = { "1": {...}} you have a number as property.
Fortunately it is not that bad because you can access this property with "array like" access msg["1"] (instead of the "normal way", msg.1). But I would consider this as bad practice and avoid this as much as possible.
Hence, as Matthew already proposes, it would be better to remove the count entry from the array on the server side, before you sent it to the client. I.e. you should get a JSON array:
[{
"tel1": "Ahemdabad",
"status": "1",
// etc.
},
{
"tel1": null,
"status": "1",
// etc.
}]
You don't need count as you can get the length of the array with msg.length and you can traverse the array with:
for(var i in msg) {
alert(msg[i].name);
}

Categories