I am passing the company information with Json, and i want also pass the areas with the same method, but something is not well, can anyone help me?
if($_GET['method']=="get_all_companies"){
$query = "SELECT company.id as c_id, company.c_name as c_name, company.c_desc as c_desc,company.c_address as c_address FROM company";
$result = mysql_query($query);
if($result){
$query_areas = "SELECT company.id as c_id, bussiness_area.* FROM company
LEFT JOIN company_area
ON company_area.id_company = company.id
LEFT JOIN bussiness_area
ON bussiness_area.id = company_area.id_area
WHERE company_id = c_id";
$result_areas = mysql_query($query_areas);
$return_arr = array();
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
$areas_arr = array();
while ($row2 = mysql_fetch_array($result_areas, MYSQL_ASSOC)) {
$row_array['c_id'] = $row['c_id'];
$row_array['c_name'] = $row['c_name'];
$row_array['c_desc'] = $row['c_desc'];
$row_array['c_address'] = $row['c_address'];
$row_array['bu_title'] = $row2['bu_title'];
array_push($return_arr,$areas_arr,$row_array);
}
}
echo json_encode($return_arr, $areas_arr);
}
else
{
echo json_encode(array('error' => 'true'));
}
}
From the first json_encode() the $areas_arr variable is not necessary.
json_encode($return_arr);
Related
I have a table1 named 'residencial' and table2 named 'propert_data'.
In 'residencial' table, I have a column named 'main_cat' which can have 3 values i.e 'Residential', 'Commercial' and 'Land'.
I have 2 web services named commercial_data.php and residential_data.php
1) commercial_data.php:
<?php
require 'include/connection.php';
$sql="SELECT * FROM residencial INNER JOIN propert_data ON propert_data.r_id = residencial.pid WHERE residencial.main_cat= 'Commercial' AND propert_data.meta_key = 'slider_images'";
$rows = array();
$result = mysqli_query($conn, $sql);
while($row = mysqli_fetch_assoc($result)) {
array_push($rows,$row);
}
$myJson = json_encode($rows);
echo $myJson;
?>
Output of this is perfect.
2) residential_data.php:
<?php
require 'include/connection.php';
$sql="SELECT * FROM residencial INNER JOIN propert_data ON propert_data.r_id = residencial.pid WHERE residencial.main_cat= 'Residential'
AND propert_data.meta_key = 'slider_images'";
$rows = array();
$result = mysqli_query($conn, $sql)or die(mysqli_error($conn));
while($row = mysqli_fetch_assoc($result)) {
array_push($rows,$row);
}
$myJson = json_encode($rows);
echo "Data:". $myJson;
?>
Output of this is: Data:
The only difference in two file is:
In file 1, I have: residencial.main_cat = 'Commercial'
In file 2, I have: residencial.main_cat = 'Residential'
What could the problem be?
You can Use like this:
while($row = mysqli_fetch_object($result)) {
$rows[] = $row;
}
So we recently set up a mySQL database for a project in our university and are currently working on the data access files written in php. In order to use the data on our front end we need it formatted as JSON. While putting an array of objects in the result of a certain object is working it won't work with 2 arrays of objects.
Working code:
<?php
include_once 'db.php';
$email = "email#online.com";
$conn = connect();
$conn->set_charset('utf8');
$resultArr = array();
$sql = "SELECT * FROM `customer` WHERE email = '$email'";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$resultArr['customer'][$row['email']] = array('email' => $row['email'], 'address' => $row['address']);
$sql2 = "SELECT id, name, address FROM shop INNER JOIN rel_shop_customer WHERE customer_email='".$row['email']."' AND rel_shop_customer.shop_id = shop.id";
$result2 = $conn->query($sql2);
while($row2 = $result2->fetch_assoc()) {
$resultArr['customer'][$row['email']]['shops'][] = $row2;
}
}
$resultArr['customer'] = array_values($resultArr['customer']);
} else {
echo "failure";
}
echo json_encode($resultArr, JSON_UNESCAPED_UNICODE);
?>
And here is the not working code:
<?php
include_once 'db.php';
$email = "email#online.com";
$conn = connect();
$conn->set_charset('utf8');
$resultArr = array();
$sql = "SELECT * FROM `customer` WHERE email = '$email'";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$resultArr['customer'][$row['email']] = array('email' => $row['email'], 'address' => $row['address']);
$sql2 = "SELECT id, name, address FROM shop INNER JOIN rel_shop_customer WHERE customer_email='".$row['email']."' AND rel_shop_customer.shop_id = shop.id";
$result2 = $conn->query($sql2);
while($row2 = $result2->fetch_assoc()) {
$resultArr['customer'][$row['email']]['shops'][] = $row2;
}
$sql3 = "SELECT img, name FROM ad INNER JOIN rel_customer_ad WHERE customer_email='".$row['email']."' AND rel_customer_ad.ad_name = ad.name";
$result3 = $conn->query($sql3);
while($row3 = $result3->fetch_assoc()) {
$resultArr['customer'][$row['email']]['ads'][] = $row3;
}
}
$resultArr['customer'] = array_values($resultArr['customer']);
} else {
echo "failure";
}
echo json_encode($resultArr, JSON_UNESCAPED_UNICODE);
?>
Both SQL queries provide the expected result when run directly on the database and I have no idea why the second one won't work in the PHP script.
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());
}
When I do this I am only getting one result back Fantasy0.1429 when I should be getting 7 different ones any one know what I am doing wrong.
$userid = $_SESSION['sess_id'];
$genreQuery = $con ->query ("select distinct(genre) from movies");
$movieGenre = array();
while($row = $genreQuery->fetch_object()) {
$movieGenre[] = $row;
}
foreach($movieGenre as $MGenre){
$query = $con ->query
(" select '$MGenre->genre' genre, IFNULL(count(*)/(select count(*) from user_movie_ratings where user_id = '$userid'),0) rating
from user_movie_ratings umr,
movies m
where umr.user_id = '$userid'
and umr.movie_id = m.id
and m.genre = '$MGenre->genre'; ");
$movieTitle = array();
while($row = $query->fetch_object()) {
$movieTitle[] = $row;
}
}
Then I echo it out later
<?php foreach($movieTitle as $movie): echo $movie->genre; echo $movie->rating; endforeach; ?>
Try to move away the instanciation of your array before the foreach like:
// Some code ...
$movieTitle = array();
foreach($movieGenre as $MGenre){
$query = $con ->query
(" select '$MGenre->genre' genre, IFNULL(count(*)/(select count(*) from user_movie_ratings where user_id = '$userid'),0) rating
from user_movie_ratings umr,
movies m
where umr.user_id = '$userid'
and umr.movie_id = m.id
and m.genre = '$MGenre->genre'; ");
while($row = $query->fetch_object()) {
$movieTitle[] = $row;
}
}
I need to encode a table content to JSON in order to insert it into a file.
The output has to be as following :
{
"name1":[{"id":"11","name":"name1","k1":"foo","k2":"bar"}],
"name2":[{"id":"12","name":"name2","k1":"foo","k2":"bar"}],
}
Indeed, each JSON "line" corresponds to the content of the mysql row and the name of each JSON array is the name of the 'name' column.
The only thing I could manage for the moment is this :
$return_arr = array();
$sql = "SELECT * FROM bo_appart";
$result = mysql_query($sql) or die(mysql_error());
$index = 0;
while ($row = mysql_fetch_assoc($result)) {
$return_arr[$index] = $row;
$index++;
}
echo json_encode($return_arr);
And here is the output I get :
[
{"id":"11","name":"name1","k1":"foo","k2":"bar"},
{"id":"12","name":"name2","k1":"foo","k2":"bar"},
]
Thanks a lot !!!
UPDATED
Working code :
$return_arr = array();
$sql = "SELECT * FROM bo_appart";
$result = mysql_query($sql) or die(mysql_error());
while ($row = mysql_fetch_assoc($result)) {
$return_arr[ $row['nom_appart'] ][] = $row;
}
echo json_encode($return_arr);
}
You were close. I noticed you want final output to be an object not an array, because the outer brackets are {} not []. So you need a different object type, and you need to use each row's name as the key for storing that row.
$return_obj = new stdClass();
$sql = "SELECT * FROM bo_appart";
$result = mysql_query($sql) or die(mysql_error());
while ($row = mysql_fetch_assoc($result)) {
$name = $row['name'];
$return_obj->$name = [$row]; // for PHP < 5.4 use array($row)
}
echo json_encode($return_obj);
This loop is enough, to create the desired JSON:
$return_arr = array();
while ($row = mysql_fetch_assoc($result)) {
$return_arr[$row['name']][] = $row; #or $return_arr[$row['name']] = [$row];
}
echo json_encode($return_arr);
I was working on it a lot of time and Create mash/mysql-json-serializer package.
https://github.com/AndreyMashukov/mysql-json-serializer
You can select Json_array of json_objects and etc. It support ManyToMany, oneToMany, manyToOne relations
SELECT JSON_ARRAYAGG(JSON_OBJECT('id',est_res.est_id,'name',est_res.est_name,'advert_groups',(SELECT JSON_ARRAYAGG(JSON_OBJECT('id',adg.adg_id,'name',adg.adg_name)) FROM advert_group adg INNER JOIN estate est_2 ON est_2.est_id = adg.adg_estate WHERE est_2.est_id = est_res.est_id))) FROM (SELECT * FROM estate est LIMIT 1 OFFSET 2) est_res
<?php
$sql = "SELECT * FROM bo_appart";
$result = mysql_query($sql) or die(mysql_error());
while ($row = mysql_fetch_array($result)) {
$return_arr[] = $row;
}
echo json_encode($return_arr);
?>