Fetching record from two table and convert into json - php

Hi I'm new in PHP and trying to get the below response using php sql but i'm not be able to find the such desire output
[{"Id":1, "name": "India", "Cities":[{"Id":1, "Name":"Mumbai", "country_id":1}, {"Id":2,"Name":"Delhi","country_id":1},
"id":3,"Name":Banglore","country_id":1}, {"Id":2, "Name":"USA", "Cities":[{"Id":6, "Name":"New York", "country_id":2},.....
I have two tables one is country based and other is city based.
I tried
<?php
include_once("config.inc.php");
$sql = "SELECT * FROM country";
$sqlCity = "SELECT * FROM city";
$cityQuery = mysqli_query($conn, $sqlCity);
$sqlQuery = mysqli_query($conn, $sql);
$mainArray = array();
if(mysqli_num_rows($cityQuery) > 0 ){
$cityResponse = array();
while($resCity = mysqli_fetch_assoc($cityQuery)){
$cityResponse[] = $resCity;
}
if(mysqli_num_rows($sqlQuery) > 0 ){
$response = array();
while($res = mysqli_fetch_assoc($sqlQuery)){
$response[] = $res;
}
foreach($cityResponse as $city){
foreach($response as $country){
if($city['country_id'] == $country['id']){
$mainArray = array("Cities" => $city);
}
}
}
echo '{"response": '.json_encode($response).', '.json_encode($mainArray).' "success": true}';
}
}else{
echo '{"response": '.json_encode($response).' "success": false}';
}
?>
currently my response showing
{"response": [{"id":"1","name":"India"},{"id":"2","name":"USA"},{"id":"3","name":"UK"}], {"Cities":{"id":"15","name":"Manchester","country_id":"3"}} "success": true}

For detail code explanation check the inline comments
Modify the SQL query with related column names
The memory you have to take care. By default memory limit in php is 128MB in 5.3
Check the code and let me know the result
<?php
$data = array();
//include your database configuration files
include_once("config.inc.php");
//execute the join query to fetch the result
$sql = "SELECT country.country_id, country.name AS country_name,".
" city.city_id, city.name AS city_name FROM country ".
" JOIN city ON city.country_id=country.country_id ".
" ORDER BY country.country_id ";
//execute query
$sqlQuery = mysqli_query($conn, $sql) or die('error exists on select query');
//check the number of rows count
if(mysqli_num_rows($sqlQuery) > 0 ){
//country id temprory array
$country_id = array();
//loop each result
while($result = mysqli_fetch_assoc($sqlQuery)){
//check the country id is already exist the only push the city entries
if(!in_array($result['country_id'],$country_id)) {
//if the city is for new country then add it to the main container
if(isset($entry) && !empty($entry)) {
array_push($data, $entry);
}
//create entry array
$entry = array();
$entry['Id'] = $result['country_id'];
$entry['name'] = $result['country_name'];
$entry['Cities'] = array();
//create cities array
$city = array();
$city['Id'] = $result['city_id'];
$city['name'] = $result['city_name'];
$city['country_id'] = $result['country_id'];
//append city entry
array_push($entry['Cities'], $city);
$country_id[] = $result['country_id'];
}
else {
//create and append city entry only
$city = array();
$city['Id'] = $result['city_id'];
$city['name'] = $result['city_name'];
$city['country_id'] = $result['country_id'];
array_push($entry['Cities'], $city);
}
}
}
//display and check the expected results
echo json_encode($data);

use like this
<?php
include_once("config.inc.php");
$sql = "SELECT * FROM country";
$sqlCity = "SELECT * FROM city";
$cityQuery = mysqli_query($conn, $sqlCity);
$sqlQuery = mysqli_query($conn, $sql);
$mainArray = array();
if(mysqli_num_rows($cityQuery) > 0 ){
$cityResponse = array();
while($resCity = mysqli_fetch_assoc($cityQuery)){
$cityResponse[] = $resCity;
}
if(mysqli_num_rows($sqlQuery) > 0 ){
$response = array();
while($res = mysqli_fetch_assoc($sqlQuery)){
$response[] = $res;
}
foreach($cityResponse as $city){
foreach($response as $country){
if($city['country_id'] == $country['id']){
$mainArray = array("Cities" => $city);
}
}
}
echo json_encode(array('result'=>'true','Cities'=>$mainArray));
}
}else{
echo json_encode(array('result'=>'false','Cities'=>$response));
}
?>

You can use try this. It actually works for me and it's cool. You can extend to 3 or more tables by editing the code.
try {
$results = array();
$query = "SELECT * FROM country";
$values = array();
$stmt = $datab->prepare($query);
$stmt->execute($values);
while($country = $stmt->fetch(PDO::FETCH_ASSOC)){
$cities = null;
$query2 = "SELECT * FROM city WHERE country_id = ?" ;
$values2 = array($country['id']);
$stmt2 = $datab->prepare($query2);
$stmt2->execute($values2);
$cities = $stmt2->fetchAll();
if($cities){
$country['cities'] = $cities;
} else {
$country['cities'] = '';
}
array_push($results, $country);
}
echo json_encode(array("Countries" => $results));
} catch (PDOException $e) {
throw new Exception($e->getMessage());
}

Related

How to make json like this from database mysql using php

{
"idbarang": "ID-75192864",
"namabarang": "Fruit Tea",
"jenisbarang": "Minuman",
"hargabarang": "6000"
}
i try this
<?php
include 'koneksi.php';
$idbarang = $_GET['id'];
if($idbarang == !null){
$query = mysqli_query($conn, "SELECT * FROM data_barang WHERE id_barang = '$idbarang'");
$result = array();
$i= 0;
while($row = mysqli_fetch_array($query)){
$result[$i]['idbarang'] = $row['id_barang'];
$result[$i]['namabarang'] = $row['nama_barang'];
$result[$i]['jenisbarang'] = $row['jenis_barang'];
$result[$i]['hargabarang'] = $row['harga_barang'];
$i++;
};
echo json_encode($result);
} else {
$query = mysqli_query($conn, "SELECT * FROM data_barang");
$result = array();
$i= 0;
while($row = mysqli_fetch_assoc($query)){
$result[$i]['idbarang'] = $row['id_barang'];
$result[$i]['namabarang'] = $row['nama_barang'];
$result[$i]['jenisbarang'] = $row['jenis_barang'];
$result[$i]['hargabarang'] = $row['harga_barang'];
$i++;
};
echo json_encode($result);
}
?>
and this the result
[
{
"idbarang": "ID-75192864",
"namabarang": "Fruit Tea",
"jenisbarang": "Minuman",
"hargabarang": "6000"
},
{
"idbarang": "ID-96037284",
"namabarang": "Sampoerna",
"jenisbarang": "Rokok",
"hargabarang": "12000"
}
]
I think you are asking why you are always going through the ELSE and never the IF. Thats because of this IF test
if($idbarang == !null){
Instead try
<?php
include 'koneksi.php';
if(!empty($_GET['id'])){
$idbarang = $_GET['id'];
You could also simplify that code quite a lot, and protect it from SQL Injection.
// Do the renaming of column names as part of the query
$sql = 'SELECT id_barang as idbarang, nama_barang as namabarang,
jenis_barang as jenisberang, jenis_barang as hargabarang
FROM data_barang';
if(!empty($_GET['id'])){
// add the WHERE clause on to the base query
$sql .= ' WHERE id_barang = ?';
$stmt = $conn->prepare($sql);
$stmt->bind_param('i', $_GET['id']);
$stmt->execute();
$res = $stmt->get_result();
} else {
$res = $conn->query($sql);
}
// as the renaming is done we can just fetch all the results and convert to a JSON document
$result = $res->fetch_all(MYSQLI_ASSOC);
echo json_encode($result);

How to get value from mssql DB in PHP

Firstly I got the workers name from BIRTHDAYS and then want to get e-mail address from USERS.There is no problem to take workers name's from Table1 but when I try to get the e-mail addresses the db returns me NULL.My DB is mssql.
<?php
include_once("connect.php");
$today = '05.07';
$today1 = $today . "%";
$sql = "SELECT NAME FROM BIRTHDAYS WHERE BIRTH LIKE '$today1' ";
$stmt = sqlsrv_query($conn,$sql);
if($stmt == false){
echo "failed";
}else{
$dizi = array();
while($rows = sqlsrv_fetch_array($stmt,SQLSRV_FETCH_ASSOC))
{
$dizi[] = array('NAME' =>$rows['NAME']);
$newarray = json_encode($dizi,JSON_UNESCAPED_UNICODE);
}
}
foreach(json_decode($newarray) as $nameObj)
{
$nameArr = (array) $nameObj;
$names = reset($nameArr);
mb_convert_case($names, MB_CASE_UPPER, 'UTF-8');
echo $sql2 = "SELECT EMAIL FROM USERS WHERE NAME = '$names' ";
echo "<br>";
$stmt2 = sqlsrv_query($conn,$sql2);
if($stmt2 == false)
{
echo "failed";
}
else
{
$dizi2 = array();
while($rows1 = sqlsrv_fetch_array($stmt2,SQLSRV_FETCH_ASSOC))
{
$dizi1[] = array('EMAIL' =>$rows['EMAIL']);
echo $newarray1 = json_encode($dizi1,JSON_UNESCAPED_UNICODE);
}
}
}
?>
while($rows1 = sqlsrv_fetch_array($stmt2,SQLSRV_FETCH_ASSOC))
{
$dizi1[] = array('EMAIL' =>$rows['EMAIL']);
echo $newarray1 = json_encode($dizi1,JSON_UNESCAPED_UNICODE);
}
you put in $rows1 and would take it from $rows NULL is correct answer :)
take $rows1['EMAIL'] and it would work
and why foreach =?
you can put the statement in while-loop like this:
while ($rows = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC)) {
$names = $rows['NAME'];
$sql2 = "SELECT EMAIL FROM USERS WHERE NAME = '$names' ";
echo "<br>";
$stmt2 = sqlsrv_query($conn, $sql2);
if ($stmt2 == false) {
echo "failed";
} else {
$dizi2 = array();
while ($rows1 = sqlsrv_fetch_array($stmt2, SQLSRV_FETCH_ASSOC)) {
$dizi1[] = array('EMAIL' => $rows1['EMAIL']);
echo $newarray1 = json_encode($dizi1, JSON_UNESCAPED_UNICODE);
}
}
}

select query through function.. to fetch data from db

How do I fetch data from db using select query in a function?
Example
function ec_select_query($student, $row = '', $fields=array()) {
$qry = "SELECT * FROM student";
$qry = mysql_query($qry);
while($row = mysql_fetch_assoc($qry)){}
return $row;
}
If you want to return all rows then first save it in an array in while loop then return this array.
function ec_select_query($student,$row='',$fields=array())
{
$qry = "SELECT * FROM student";
$qry = mysql_query($qry);
$result = array();
while($row = mysql_fetch_assoc($qry))
{
$result[] = $row;
}
return $result;
}
Its is running code. Modify it according to your needs
$con = mysql_connect('localhost','root','') or die("Unable to connect to MySQL");
mysql_select_db('demo', $con) or die("Database not found");
function ec_select_query($student)
{
$query = "SELECT * FROM $student";
$result = mysql_query($query);
$row = array();
$getData = array();
while($row = mysql_fetch_array($result))
{
$getData[]=$row;
}
return $getData;
}
$information = ec_select_query('accountplans');
echo "<pre>"; print_r($information); die;
Try it
function select_query($table, $where=array(),$fields=array()){
$select_fields = $table."*";
if(!empty($fields) && is_array($fields)){
$select_fields = implode(",", $fields);
}
$sql = "select ".$select_fields." from ".$table." where 1=1 ";
if(!empty($where) && is_array($where)){
foreach ($where as $key => $value) {
$sql .= " AND ".$value;
}
}
$query = mysql_query($sql);
$result = array();
while($row = mysql_fetch_assoc($result)){
$result[] = $row;
}
return $result;
}
Call Function
$fields = array("id","name","city");
$where = array('name = "abc"','city like "aaa"');
$students = select_query("studendts", $where, $fields);
This code might help you :
function ec_select_query($student,$row='',$fields=array())
{
$q = "SELECT * FROM student";
$q = mysql_query($qry);
while($row = mysql_fetch_array($qry))
{
return $row;
}
}
It is easiest way to produce entire data in array
function db_set_recordset($sql) {
$qry = mysql_query($sql);
$row= array();
while($out = mysql_fetch_assoc($qry)) {
$row[] = $out;
}
return $row;
}
$qry = "SELECT * FROM student";
$result = db_set_recordset($qry);

Passing multiple dimension array in PHP

MySql query returns me a multi-dimensional array :
function d4g_get_contributions_info($profile_id)
{
$query = "select * from contributions where `project_id` = $profile_id";
$row = mysql_query($query) or die("Error getting profile information , Reason : " . mysql_error());
$contributions = array();
if(!mysql_num_rows($row)) echo "No Contributors";
while($fetched = mysql_fetch_array($row, MYSQL_ASSOC))
{
$contributions[$cnt]['user_id'] = $fetched['user_id'];
$contributions[$cnt]['ammount'] = $fetched['ammount'];
$contributions[$cnt]['date'] = $fetched['date'];
$cnt++;
}
return $contributions;
}
Now I need to print the values in the page where I had called this function. How do I do that ?
change the function like this:
while($fetched = mysql_fetch_array($row, MYSQL_ASSOC))
{
$contributions[] = array('user_id' => $fetched['user_id'],
'ammount' => $fetched['ammount'],
'date' => $fetched['date']);
}
return $contributions;
Then try below:
$profile_id = 1; // sample id
$result = d4g_get_contributions_info($profile_id);
foreach($result as $row){
$user_id = $row['user_id']
// Continue like this
}

check table from my sql query

Hello I'm checking duplicated data from tables. I have a problem that from where data selected. My code is:
$sub_cat = array();
$select = array("core_network","daisy_chain", "rf_bts", "rf_power", "rf_transmission");
$d='0';
for ($i=0;$i<=4;$i++){
$SQL = "SELECT sub_cat FROM (".$select[$i].") WHERE location=('".$id."')";
$result = mysql_query($SQL);
$cs=$d;
if ($result) {
while ($db_field = mysql_fetch_array($result)) {
if(!in_array($db_field['sub_cat'],$sub_cat)) {
$sub_cat[]= $db_field['sub_cat'];
$cs++;
$d=$cs;
$d--;
}
}
}
I need to know that sub_cat selected from which $select[i]. How to find it?
To get the values, do this:
$sub_cat = array();
$select = array("core_network","daisy_chain", "rf_bts", "rf_power", "rf_transmission");
$d='0';
for ($i=0;$i<=4;$i++){
$SQL = "SELECT sub_cat FROM (" . $select[$i] . ") WHERE location=('".$id."')";
$result = mysql_query($SQL); // deprecated - use PDO
$cs = $d;
if ($result) {
while ($db_field = mysql_fetch_array($result)) {
if(!in_array($db_field['sub_cat'], $sub_cat)) {
$table = $select[$i];
$sub_cat[$table][] = $db_field['sub_cat'];
// I have no clue what's going on here in your example:
$cs++;
$d=$cs;
$d--;
}
}
}
}
Then, to retrieve it:
foreach ($sub_cat as $table_name => $values) {
foreach ($values as $row) {
// output values here
}
}

Categories