How to create JSON API service from mysql database in php - php

I have following mysql database table
id | majorFoodName | cropName | foodType | foodName | quantity | form
1 | Recipe1 | Rice | Breakfast | Foodname1 | 500+60 | 2000
4 | Recipe2 | Rice | Breakfast | Foodname2 | 500 | 1000
6 | Recipe1 | Wheat | Breakfast | Foodname2 | 518 | 1000
I have written following php code to give JSON API output
$sql = "SELECT * FROM food WHERE cropName = 'Rice' AND foodName =
'Foodname1' ";
$result = mysqli_query($connect, $sql);
$num_rows = mysqli_num_rows($result);
if ($num_rows > 0) {
$jsonData = array();
while ($array = mysqli_fetch_row($result)) {
$jsonData[] = $array;
}
}
class Emp {
public $majorFoods = "";
}
$e = new Emp();
$e->majorFoods = $jsonData;
header('Content-type: application/json');
echo json_encode($e);
I am getting following JSON output
{
"majorFoods": [
[
"1",
"Recipe1",
"Rice",
"Breakfast",
"Foodname1",
"500+60",
"2000"
]
]
}
I need to give following API JSON format for all cropName and all foodName
{
"Rice": [
{
"foodName1": {
"majorFoodName": "Receipe1",
"quantity": "500+60",
"form": "2000" }
"foodName2": {
"majorFoodName": "Receipe2",
"quantity": "500",
"form": "1000" }
]
"Wheat": [
{
"foodName2": {
"majorFoodName": "Receipe1",
"quantity": "518",
"form": "1000" }
]
}
Kindly help in improving the php code to get desired API JSON response.

When your building up your array of data, use the crop type as the main index and create sub arrays of the extra data you need to store.
while ($array = mysqli_fetch_assoc($result)) {
$cropData = array ( $array['foodName'] =>
array( 'majorFoodName' => $array['majorFoodName'],
'quantity' => $array['quantity'],
'form' => $array['form'] ));
$jsonData[$array['cropName']][] = $cropData;
}
Note that I use mysqli_fetch_assoc so that I can refer to the result fields with the column names.
The line
$jsonData[$array['cropName']][] = $cropData;
Accumulates all of the data for a particular crop name together, adding the new data to the end of the array (using []).

Related

implemented counting data before insert using CI

I'm making a OffDayWork form, which I expect that every employee only can request their off-day-work maximum of 12 times. I use this as my reference, but it still has not worked.
This is my structure table :
- tabel_cuti
holID | holEmpId | holName |
---------------------------|
1 | 1 | Ied |
---------------------------|
2 | 3 | exp1 |
---------------------------|
3 | 4 | exp2 |
---------------------------|
4 | 1 | Married |
---------------------------|
I tried this in my model
EmployeeModel
public function HolidayRegister($data)
{
$this->db->insert('tbl_cuti',$data);
return true;
}
public function HitungCuti($data)
{
$this->db->select('count(table_cuti.holID) as countcuti');
$this->db->from('tabel_cuti');
$this->db->join('tabel_pegawai','tabel_cuti.holEmpId = tabel_pegawai.empID');
$this->db->group_by('table_cuti.holEmpId');
$totalhol = $this->db->get();
}
And my controller (Employee)
public function HolidayRegister()
{
if(!empty($_POST))
{
$data = array('holEmpId' => $this->input->post('employee_id'),
'holName' => $this->input->post('holiday_name'),
'holDate' => $this->input->post('holiday_date'),
'holDescription' => $this->input->post('description'),
'created_date' => date('Y-m-d H:i:s'),
);
$result = $this->EmployeeModel->HitungCuti($data);
if($result -> num_rows() < 12)
{
$this->EmployeeModel->HolidayRegister($data);
}
else
{
$data = array('holEmpId' => $this->input->post('employee_id'),
'holName' => $this->input->post('holiday_name'),
'holDate' => $this->input->post('holiday_date'),
'holDescription' => $this->input->post('description'),
'created_date' => date('Y-m-d H:i:s'),
);
$this->session->set_flashdata('SUCCESSMSG','Tidak ada kesempatan cuti');
$data['getEmployee'] = $this->EmployeeModel->getEmployee();
$this->load->view('holiday_register',$data);
}
}
else
{
$this->session->set_flashdata('SUCCESSMSG', "Holiday Register Successfully!!");
redirect('view-holiday');
}
}
Its my first time trying CI, so please i need your help.
On HitungCuti() method, you are counting all of the employee holiday data. You need to limit the selection only for the submitted employee data :
public function HitungCuti($data)
{
$this->db->select('holID');
$totalhol = $this->db->get_where('tabel_cuti', array('holEmpId' => $data['holEmpId'])); // only search for the specified employee ID
return $totalhol;
}

JSON Array to PHP Array Multidimensional

i have json data like this :
{
"response": {
"count": 212,
"list": [
{
"code": "02007",
"name": "swept the room",
"rate": 750000,
"withValue": false
},
{
"code": "02005",
"name": "mop room",
"rate": 600000,
"withValue": false
},
{
"code": "02003",
"name": "buying food",
"rate": 175000,
"withValue": false
}
]
},
"metaData": {
"message": "OK",
"code": 200
}
}
and i have table schema like this :
mysql> desc master_service;
+----------------+-------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+----------------+-------------+------+-----+---------+----------------+
| id | int(25) | NO | PRI | NULL | auto_increment |
| code | varchar(10) | YES | | NULL | |
| name | varchar(20) | YES | | NULL | |
| rate | double | YES | | NULL | |
| withvalue | tinyint(1) | YES | | NULL | |
+----------------+-------------+------+-----+---------+----------------+
and my coding like this.
//using php pdo
include_once 'db_connect.php';
$data = json_decode($response, true);
$tempservice = array();
if(isset($data['response']) && isset($data['response']['list']))
{
//use foreach on ['response']['list'] index - here are teachers data stored
foreach($data['response']['list'] as $service)
$tempservice[$kesadaran['code']] = $service['name'];
}
foreach($tempservice as $key =>$value) {
$sql = "insert into master_service(code,name) Values ('$key','$value')";
$st = $dbh->prepare($sql);
$st->execute ($data);
}
it can only save the database in the form of codes and names. i want rate and withValue can be save on database
Just use a foreach loop and add the missing columns, no need for a restructured $tempservice array:
include_once 'db_connect.php';
$data = json_decode($response, true);
// Simplified if, checking for isset($data['response') is redundant
if (isset($data['response']['list']))
{
// Prepare the statement using placeholders
$sql = "INSERT INTO master_service (code,name,rate,withValue) VALUES (:code,:name,:rate,:withValue)";
$stmt = $dbh->prepare($sql);
foreach($data['response']['list'] as $row)
{
// Execute query with parameters
$stmt->execute($row);
}
}
Important: I replaced the variables in your query with placeholders. This way it is safe against SQL Injection. I also put the prepare outside of the loop so that it doesn't "reprepare" on every iteration.
You can try this:-
include_once 'db_connect.php';
$data = json_decode($response, true);
$tempservice = [];
if(isset($data['response']) && isset($data['response']['list'])){
//use foreach on ['response']['list'] index - here are teachers data stored
foreach($data['response']['list'] as $service){
$withValue = ($service['withValue']) ? 1 : 0;
$tempservice[$service['code']] = ['name'=>$service['name'], 'rate'=>$service['rate'], 'withvalue'=>$withValue];
}
}
foreach($tempservice as $key =>$value) {
$sql = "insert into master_service(code, name, rate, withvalue) Values ('$key', '".$value['name']."', '".$value['rate']."', '".$value['withvalue']."')";
$st = $dbh->prepare($sql);
$st->execute ();
}
Note: please fix any syntax error. Also you can skip creating tempservice array and can execute insert sql there
foreach($data['response']['list'] as $value) {
$sql = "insert into master_service(code,name,rate,withvalue) Values ('{$value['code']}','{$value['name']}', '{$value['rate']}', '{$value['withValue']}')";
$st = $dbh->prepare($sql);
$st->execute ($data);
}
sorry i forgot the true parameter on json_decode.. edited

Compare 2 arrays and retrieve the differences using PHP

I'm not a PHP expert but i'm trying Compare 2 arrays ( database relations and schema) in PHP, I need retrieve the differences between those 2 array, I'm using this php code
<?php
function maxEntities($rela, $db){
$maxenty = array();
$found = false;
foreach ($rela as $valor1) {
print $valor1[0] . " | ";
}
print " <br \>";
foreach ($db as $valor2) {
print $valor2[0] . " | ";
}
$maxenty = array_diff($rela[0], $db[0]);
print " <br \> <br \>";
foreach ($maxenty as $valor) {
print " " . $valor;
}
}
and this code give me this output
Sale | Customer | Sale_Fee | Sale | Location | Sale | Sale | Sale_Iten | Product | Customer | Location | Sale_Iten | Sale_Fee | Region |
Customer | Customer_Type | Fee_Type | Location | Location_Type | Period | Product | Product_Type | Region | Sale | Sale_Fee | Sale_Iten | State |
Sale Customer_Cust_Id
and the output i expect is
Period, Customer_Type, State, Location Type, Product Type and Fee Type
how i can solve my problem ?
i also tried with foreach, but give me also a wrong output
foreach ($rela as $relaV) {
foreach ($db as $dbV) {
if ($dbV[0] == $relaV[0]) {
$found = true;
}
if (!$found) {
$found = false;
$maxenty[] = $dbV[0];
}
}
}
in this case my output was
Customer
Customer_Type
Fee_Type
Location
Location_Type
Period
Product
Product_Type
Region
and Customer, Region, Location are in both arrays
It is not very clear, how your arrays are structured. From your code so far I guess the following structures:
$rela = array(array('Sale'), array('Customer'), array('Sale_Fee'), array('Sale'), array('Location'), array('Sale'), array('Sale'), array('Sale_Iten'), array('Product'), array('Customer'), array('Location'), array('Sale_Iten'), array('Sale_Fee'), array('Region'));
$db = array(array('Customer'), array('Customer_Type'), array('Fee_Type'), array('Location'), array('Location_Type'), array('Period'), array('Product'), array('Product_Type'), array('Region'), array('Sale'), array('Sale_Fee'), array('Sale_Iten'), array('State'));
If this is the structure of your arrays, then you can use the following code to get the difference (adopted from your foreach-approach, there may be other ways):
$maxenty = array();
foreach ($db as $dbValue) {
$found = false;
foreach ($rela as $relaValue) {
if ($relaValue[0] == $dbValue[0]) {
$found = true;
break;
}
}
if (!$found) {
$maxenty[] = $dbValue[0];
}
}
print_r($maxenty);
This will give you the $maxenty as follows:
Array
(
[0] => Customer_Type
[1] => Fee_Type
[2] => Location_Type
[3] => Period
[4] => Product_Type
[5] => State
)

PHP tree menu, bottom-up

I'm having some issues getting a tree menu to work from bottom-up.
I already have a script to work from top-down, which works fine.
This is a very simplified version of my table:
+-----+-----------+--------------------+
| uid | parent_id | page_address |
+-----+-----------+--------------------+
| 1 | 0 | index.php |
| 2 | 0 | login.php |
| 3 | 2 | dashboard.php |
| 4 | 3 | bookings.php |
| 5 | 3 | documents.php |
| 6 | 4 | changebookings.php |
| 7 | 4 | activities.php |
+-----+-----------+--------------------+
The page_address field is unique.
I can work out what page the user is currently on, for example changebookings.php
I would then like a menu to look like this:
login.php
dashboard.php
bookings.php
changebookings.php
activities.php
documents.php
However, the closest I've got so far is the following tree:
login.php
bookings.php
changebookings.php
As you can see, my script currently only returns the actual parent, and not a list of links currently in the parent.
For those interested, the script I use in total is at the bottom of this post.
Is there any easier way to get the bottom-up tree as required?
Many thanks
Phil
EDIT:
I've finally got the code to work, for future users who stumble upon this post, I have added the functionality below:
$dataRows = $databaseQuery->fetchAll(); // Get all the tree menu records
$dataRows = $result->fetchAll(PDO::FETCH_ASSOC);
foreach($dataRows as $row)
{
if($row['link_address']==substr($_SERVER['PHP_SELF'], 1, strlen($_SERVER['PHP_SELF'])-1))
{
$startingId = $row['parent_id'];
}
}
$menuTree = $this->constructChildTree($dataRows, $startingId);
private function constructChildTree(array $rows, $parentId, $nesting = 0)
{
$menu = array();
if(!in_array($nesting, $this->nestingData))
{
$this->nestingData[] = $nesting;
}
foreach($rows as $row)
{
if($row['parent_id']==$parentId && $parentId!=0)
{
$menu[] = $row['link_address'];
$newParentId = $this->getNextParent($rows, $row['parent_id']);
$parentChildren = $this->constructChildTree($rows, $newParentId, ($nesting+1));
if(count($parentChildren)>0)
{
foreach($parentChildren as $menuItem)
{
$menu[] = 'NESTING' . $nesting . '::' . $menuItem;
}
}
}
}
return $menu;
}
private function getNextParent($rows, $parentId)
{
foreach($rows as $row)
{
if($row['uid']==$parentId)
{
return $row['parent_id'];
}
}
}
Without reading your code you should be doing:
1) Get current page, look at parent ID.
2) Load all with that parent ID.
3) Get next Parent ID using current Parent ID as ID.
4) If new parent ID != 0, goto step 2 passing in the new Parent ID.
Sounds like you just need to edit your script to include ALL pages with the given ID as their parent ID.
<?PHP
$sql = "SELECT * FROM TABLE WHERE table parent_id=0";
$result = mysql_query($sql);
while($perant_menu = mysql_fetch_array($result))
{
echo display_child($perant_menu["uid"],$perant_menu["page_address"]);
}
// Recursive function
function display_child($parent_id,$name)
{
$sql= "SELECT * FROM table where parent_id = $parent_id";
$result = mysql_query($sql);
if(mysql_num_rows($result)>0)
{
while($menu = mysql_fetch_array($result))
{
echo display_child($menu["id"],$menu["page_address"]);
}
}
else
{
echo $name;
}
}
?>

Querying results by categories and displaying everything as list

I've a table, basically its something like
------------------
id | name | type
------------------
1 | name1 | type1
2 | name2 | type2
3 | name3 | type3
------------------
I would like to query it and display it into something like
type1
- name1
- and so on...
type2
- name2
- and so on...
type3
- name 3
- and so on...
I am also looking to display it as a JSON file which is something like
[
{
"type1": {
"name": "name1"
},
"type2": {
"name": "name2"
},
"type3": {
"name": "name3"
}
}
]
So, may I know the best way to do it?
Using loops to query the type, then selecting the categories and displaying it by type?
Edit :
After searching high and low in the internet. I've found this : http://www.tommylacroix.com/2008/09/10/php-design-pattern-building-a-tree/
Hence formulated this code for my needs. Not sure if it's efficient :
<?php
$query = "SELECT * FROM TABLE";
$list = array();
$result = mysql_query($query);
while($row = mysql_fetch_array($result)){
if(!$list[$row['type']])
{
$list[$row['type']] = array();
}
array_push($list[$location['type']],&$row['name']) ;
}
?>
Try This.... also see the result output below
SELECT id,CONCAT_WS(',',type,name) as result FROM table GROUP BY id
<?php
$sql= mysql_query("SELECT id,CONCAT_WS(',',type,name) as result FROM table GROUP BY id");
$data = array();
$i=0;
while($row = mysql_fetch_array($sql)){
$ex_res = explode(",",$row['result']);
$data[$ex_res[0]]['name'] = $ex_res[1];
$i++;
}
$a = json_encode($data);
print_r($a);
?>
Result Output
{"type1":{"name":"name1"},"type2":{"name":"name2"},"type3":{"name":"name3"}}

Categories