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);
?>
Related
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.
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
Here i have two tables, i want get the results from this two tables.i tried lot but i am unable to get the exact results can you please any help me, i am using this application in codeiniter.
First Table
new_staff
staff_id firstName Mobile userType
1 Soupranjali 9986125566 Teacher
2 Sujata 8553880306 Teacher
Second Table
new_student
student_id first_Name fatherMobile user_type
1 janarthan 8553880306 Student
2 Santanu 8277904354 Student
3 Sarvan 8553880306 Student
here 8553880306 both table this mobile number is present, so want get to the both table results
Expected Results
{
"status": "Success",
"Profile": [
{
"staff_id": "2",
"firstName": "Sujata",
"userType" : "Teacher"
},
{
"student_id": "1",
"firstName": "janarthan",
"user_type" : "Student"
},
{
"student_id": "3",
"firstName": "Sarvan",
"user_type" : "Student"
}
]
}
So tried like this but i unable to get the answer, so please anyone help me,
my model
public function android_memberList($mobile)
{
$this->db->select('new_staff.staff_id, new_staff.firstName, new_staff.userType, new_student.student_id, new_student.first_Name, new_student.user_type');
$this->db->from('new_staff');
$this->db->join('new_student', 'new_student.fatherMobile = new_staff.Mobile');
$query = $this->db->get();
# result_array is used to convert the data into an array
$result = $query->result_array();
echo json_encode($result);
}
Based on my query it is returning the out put like this, but this is not my expected json fomat
[
{
"staff_id": "2",
"firstName": "Sujata",
"userType": "Teacher",
"student_id": "1",
"first_Name": "janarthan",
"user_type": "Student"
},
{
"staff_id": "2",
"firstName": "Sujata",
"userType": "Teacher",
"student_id": "2",
"first_Name": "Santanu",
"user_type": "Student"
}
]
updated answer
{
"status": "Success",
"Profile": [
{
"staff_id": "2",
"firstName": "Sujata",
"userType": "Teacher"
},
{
"staff_id": "2",
"firstName": "Sujata",
"userType": "Teacher"
},
{
"student_id": "1",
"first_Name": "janarthan",
"user_type": "Student"
},
{
"student_id": "2",
"first_Name": "Santanu",
"user_type": "Student"
}
]
}
$this->db->join('new_student', 'new_student.fatherMobile = new_staff.Mobile','left');
Please replace this line in your code and check, I think it's working and that you'd get the data as you want.
You are using MySQL join to merge data from 2 tables, which will never get you the desired result. You can use union to merge data from both the tables.In your case, the problem is your field names are different in both the tables.
Solution 1:
In SQL generalize the column names using alias, the problem is in your json array, you will get generalize keys.
Solution 2:
Run 2 different queries, get data in 2 different arrays, merge 2 arrays and get the desired result. I am implementing the 2nd solution here.
public function android_memberList($mobile)
{
$this->db->select('distinct(new_staff.staff_id), new_staff.firstName, new_staff.userType');
$this->db->from('new_staff');
$this->db->join('new_student', 'new_student.fatherMobile = new_staff.Mobile');
$query1 = $this->db->get();
# result_array is used to convert the data into an array
$result_new_staff = $query1->result_array();
$this->db->select('distinctnew_student.student_id), new_student.first_Name, new_student.user_type');
$this->db->from('new_staff');
$this->db->join('new_student', 'new_student.fatherMobile = new_staff.Mobile');
$query2 = $this->db->get();
# result_array is used to convert the data into an array
$result_new_student = $query2->result_array();
$final_result=array_merge($result_new_staff,$result_new_student);
$result["status"] = "Success";
$result["Profile"] = $final_result;
echo json_encode($result);
}
You can use join to get two table data with one key left join is best option for this
You can try like this
$this->db->join('new_student', 'new_student.fatherMobile = new_staff.Mobile','left');
You can try this query in your codeigniter project which will give you all columns with new names.
Or you can modify column names with your compatibility.
$this->db->select('ns1.student_id, ns1.first_name as student_first_name');
$this->db->select('ns1.fatherMobile, ns1.user_type as student_user_type');
$this->db->select('ns2.firstName as staff_first_name');
$this->db->select('ns2.Mobile as staff_mobile, ns2.userType as staff_user_type');
$this->db->from('new_student as ns1');
$this->db->join('new_staff as ns2', 'ns2.Mobile = ns1.fatherMobile', 'left');
$this->db->get()->result_array();
You can see your query solved here https://dbfiddle.uk/?rdbms=mysql_8.0&fiddle=0288bef1b4f753a134000ae73d6bd58d
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);
}
Here is my JSON file which is called (inventory.json). How do I parse the json so I can get all of the inventory's tag_name in the "Descriptions" array? Since the Inventory array's classid points out to the description's id/classid, it seems possible to get each of the inventory's tag from the description but I have no idea to do it.
I read something about recursive array iterator and for each but I have no idea which one is appropriate in this circumstance. I am very new here so please be kind! Thank you.
{
"Inventory": {
"7905269096": {
"id": "7905269096",
"classid": "771158876",
"instanceid": "782509058",
"amount": "1",
"pos": 1
},
"7832200468": {
"id": "7832200468",
"classid": "626495772",
"instanceid": "1463199080",
"amount": "1",
"pos": 2
},
"7832199378": {
"id": "7832199378",
"classid": "626495770",
"instanceid": "1463199082",
"amount": "1",
"pos": 3
},
"Descriptions": {
"771158876": {
"classid": "771158876",
"instanceid": "782509058",
"tags": [{
"tag_name": "unique",
"name": "standard"
}]
}
}
}
}
Your JSON string is invalid, but hopefully this answer will lead you on the right path to your desired result.
First, make it into a PHP array:
$jsonArray = /* your json array */;
$phpArray = json_decode($jsonArray, true);
Then you can iterate through one of the arrays (the "Inventory" one) and find the relevant tag name:
//Create a new array to hold the key=>value data
$combined = [];
foreach($phpArray["Inventory"] as $i => $v){
//Find the relevant key in the Descriptions array and
//push this information information to the $combined array
$combined[$i] = $phpArray["Descriptions"][$i]["tags"]["tag_name"];
/* The above is essentially the same as
$combined["7905269096"] = "unique"; */
}
Then, $combined will be a key/value array where the key is the ID (e.g. "7905269096") and the value will be the tag name (e.g. "unique").