how to solve anonymous array? - php

this is my php sql code
//fetch table rows from mysql db
$sql = "select * from tbl_sample";
$result = mysqli_query($connection, $sql) or die("Error in Selecting " . mysqli_error($connection));
//create an array
$emparray = array();
while($row =mysqli_fetch_assoc($result))
{
$emparray[] = $row;
}
$info = json_encode($emparray);
echo $info;
//close the db connection
mysqli_close($connection);
?>
when I run this code i'm getting an an anonymous json array like this.
[{"id":"1","country":"india","domain":"MBA"},{"id":"2","country":"england","domain":"cricket"},{"id":"3","country":"pakistan","domain":"MTECH"},{"id":"4","country":"newzeland","domain":"bba"}]
is there a way to give this array a name because without a named array I don't know how to use this json data for dust.js template. If not suggest me how I can use this data for my templating. thank you.

//fetch table rows from mysql db
$sql = "select * from tbl_sample";
$result = mysqli_query($connection, $sql) or die("Error in Selecting " . mysqli_error($connection));
//create an array
$emparray = array();
while($row =mysqli_fetch_assoc($result))
{
$emparray[] = $row;
}
$mydata['my_data'] = $emparray;
$info = json_encode($mydata);
echo $info;
//close the db connection
mysqli_close($connection);
Try this. Your data will look like this
{"my_data":[{"id":"1","country":"india","domain":"MBA"},{"id":"2","country":"england","domain":"cricket"},{"id":"3","country":"pakistan","domain":"MTECH"},{"id":"4","country":"newzeland","domain":"bba"}]}

When building your array, you need to setup your keys using whichever unique value you want. For example:
while($row =mysqli_fetch_assoc($result)) {
$key = $row['domain'];
$emparray[$key] = $row;
}
This will result in your JSON being keyed with the domain value.

Related

How to get entire column from database and store it in an array using php?

My table's name is userdetails, it has four attributes named name, username, mobile and password. I want to get all the mobile numbers and store it in an array using php.
I have used the following php code
if($_SERVER['REQUEST_METHOD']=='GET'){
require_once('dbConnect.php');
$mobile = $_GET['mobile'];
$sql = "SELECT MOBILE FROM USERDETAILS";
$r = mysqli_query($con,$sql);
$res = mysqli_fetch_array($r);
$result = array();
array_push($result,array(
"MOBILE"=>$res['MOBILE']
)
);
echo json_encode(array("result"=>$result));
mysqli_close($con);
}
but all I am getting is the first entry of the database.
Please help.
You should loop through the records by doing the following:
$result = [];
while ($array = mysqli_fetch_array($r)) {
$result[] = $array['MOBILE'];
}
echo json_encode($result);
For getting all number of column use while loop as
$jsonData = array();// initialized you array
while ($array = mysqli_fetch_array($r,MYSQLI_ASSOC)) {// add MYSQLI_ASSOC to get associative array
$jsonData[] = $res['MOBILE'];// store data into array
}
echo json_encode($jsonData);// convert in into json
Try this:
$result = mysqli_query($con,$sql);
$mob = Array();
while ($row = mysqli_fetch_array($result,MYSQLI_ASSOC)) {
$mob[] = $row['MOBILE'];
}

make json array from mysql data using php

I want to take some data from my mysql database, and pass it to a json array, so that I can use it in my android application.
But so far I'm having trouble getting any data from the mysql db, when i run my php code in the browser to check output, i get a blank screen. Can someone help ?
CODE:
<?php
$connection = mysqli_connect("localhost","testUser","root","EasyFridge") or die("error". mysqli_error($connection));
$sql = "select * from product";
$result = mysqli_query($connection, $sql);
$emparray = array();
while($row = mysqli_fetch_assoc($result)){
$emparray[] = array("product" => $row);
}
echo json_encode($emparray);
mysqli_close($connection);
?>
I suggest you look at error log of PHP. It's very likely that the script exceeded max memory available. If so, you may try following actions:
Increase max memory in php.ini file by setting memory_limit parameter or call in your code ini_set('memory_limit', '2048M');;
Break your data into pages with more appropriate count of objects returned.
UPDATE:
Found the error, was missing a charset decoding statement, so just added:
<?php
//open connection to mysql db
$connection = mysqli_connect("localhost","testUser","root", "EasyFridge") or die("Error " . mysqli_error($connection));
//fetch table rows from mysql db
$sql = "SELECT * FROM product";
mysqli_set_charset($connection, "utf8"); //ADDED THIS LINE!!
$result = mysqli_query($connection, $sql) or die("Error in Selecting " . mysqli_error($connection));
error_reporting(E_ALL);
$returnarray = array();
//create an array
while($row = mysqli_fetch_array($result, MYSQL_ASSOC))
{
//$emparray[] = $row[];
$emparray['id'] = $row['id'];
$emparray['name'] = $row['name'];
$emparray['placement_date'] = $row['placement_date'];
$emparray['removal_date'] = $row['removal_date'];
$emparray['type'] = $row['type'];
array_push($returnarray, $emparray);
}
//var_dump($returnarray);
echo json_encode($returnarray);
//close the db connection
mysqli_close($connection);
?>

PHP code to encode DB data in JSON not working

I'm currently stuck with some PHP code. I want to access a table in my database and retrieve the data in a JSON format. Therefore, I tried the following code :
<?php
$con = mysqli_connect("......","username","pwd","DBName");
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql = "SELECT * FROM users";
if ($result = mysql_query($con, $sql))
{
$resultArray = array();
$tempArray = array();
while($row = $result->fetch_object())
{
$tempArray = $row;
array_push($resultArray, $tempArray);
}
echo json_encode($resultArray);
}
mysqli_close($con);
?>
However, it's getting me an empty page. It worked once but only with a special number of row in the table, so not very efficient as you might guess.
Does anybody have an idea why i'm getting those weird results?
EDIT 1 :
I Just tried to add this to my code :
echo json_encode($resultArray);
echo json_last_error();
And it's returning me 5. It seems to be an error from the data encoding in my table. Therefore I added that code :
$tempArray = array_map('utf8_encode', $row)
array_push($resultArray, $tempArray);
And I got the following output : [null,null,null]0 (The zero comes from the echo json_last_error();)
So here I am, can anybody help me with this ?
I would start by changing if ($result = mysql_query($con, $sql)) to if ($result = mysqli_query($con, $sql)) because they are different database extensions
Another thing would be to change while($row = $result->fetch_object()) to while ($row = mysqli_fetch_object($result)) { (Procedural style vs. Object oriented style)
If you still see blank screen, try adding error_reporting(E_ALL); at the top of your script, and you'll be able to know exactly where the bug is
<?php
$con = mysqli_connect("......","username","pwd","DBName")
or die("Failed to connect to MySQL: " . mysqli_connect_error());
$sql = "SELECT * FROM users";
$query = mysqli_query($con, $sql) or die ("Failed to execute query")
if ($result = $query)
{
$resultArray = array();
while($row = $result->fetch_object())
{
array_push($resultArray, $row);
}
$result->close()
echo json_encode($resultArray);
}
mysqli_close($con);
?>
This code works for me, try it out:
<?php
$con = mysqli_connect("......","username","pwd","DBName");
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql = "SELECT * FROM users";
if ($result = mysqli_query($con, $sql))
{
while($row = $result->fetch_object())
{
$resultArray[] = $row;
}
echo json_encode($resultArray);
}
mysqli_close($con);
?>
EDIT 1:
As a test replace this code:
while($row = $result->fetch_object())
{
$resultArray[] = $row;
}
echo json_encode($resultArray);
with this code:
while($row = $result->fetch_assoc())
{
print_r($row);
}
What output do you get?
I finally found a solution ! That was indeed an encoding problem, the json_encode() function accepts only strings encoded in utf8. I changed the interclassement of my table to utf8_general_ci and I modified my code as follows :
<?php
//Create Database connection
$db = mysql_connect(".....","username","pwd");
if (!$db) {
die('Could not connect to db: ' . mysql_error());
}
//Select the Database
mysql_select_db("DBName",$db);
//Replace * in the query with the column names.
$result = mysql_query("SELECT * FROM users", $db);
//Create an array
$json_response = array();
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
$row_array['id'] = $row['id'];
$row_array['name'] = utf8_encode($row['name']);
$row_array['lastName'] = utf8_encode($row['lastName']);
//push the values in the array
array_push($json_response,$row_array);
}
echo json_encode($json_response);
//Close the database connection
fclose($db);
?>
And I got the expected output.

Converting a mysql query to a JSON object using php?

I am trying to convert a mySQL query into a JSON object. This works:
<?php
// load in mysql server configuration (connection string, user/pw, etc)
include 'mysqlConfig.php';
$year = $_GET['year'];
// connect to the database
#mysql_select_db($dsn) or die( "Unable to select database");
// outputs the db as lines of text.
$result = mysql_query("SELECT COUNTY, COUNT(TYPE) AS 'type' from data WHERE DATE between '2000-01-01' and '2000-12-31' GROUP BY COUNTY");
$rows = array();
while($r = mysql_fetch_assoc($result)) {
$rows[] = $r;
}
echo json_encode($rows);
mysql_close();
?>
But I get this output:
[{"COUNTY":"Carlow","type":"121"},{"COUNTY":"Cavan","type":"130"},{"COUNTY":"Clare","type":"112"},{"COUNTY":"Cork","type":"833"},{"COUNTY":"Donegal","type":"264"},{"COUNTY":"Dublin","type":"2457"},{"COUNTY":"Galway","type":"287"},{"COUNTY":"Kerry","type":"227"},{"COUNTY":"Kildare","type":"300"},{"COUNTY":"Kilkenny","type":"139"},{"COUNTY":"Laois","type":"123"},{"COUNTY":"Leitrim","type":"39"},{"COUNTY":"Limerick","type":"370"},{"COUNTY":"Longford","type":"85"},{"COUNTY":"Louth","type":"257"},{"COUNTY":"Mayo","type":"231"},{"COUNTY":"Meath","type":"268"},{"COUNTY":"Monaghan","type":"136"},{"COUNTY":"Offaly","type":"97"},{"COUNTY":"Roscommon","type":"115"},{"COUNTY":"Sligo","type":"113"},{"COUNTY":"Tipperary","type":"249"},{"COUNTY":"Waterford","type":"205"},{"COUNTY":"Westmeath","type":"118"},{"COUNTY":"Wexford","type":"246"},{"COUNTY":"Wicklow","type":"235"}]
whereas this is the format I am looking for:
{"Carlow":3,"Cavan":4,"Clare":5,"Cork":3,"Donegal":4,"Dublin":5,"Galway":4,"Kerry":5,"Kildare":5,"Kilkenny":12,"Laois":4,"Leitrim":4,"Limerick":4,"Longford":4,"Louth":4,"Mayo":5,"Meath":3,"Monaghan":5,"Offaly":4,"Roscommon":3,"Sligo":3,"Tipperary":4,"Waterford":2,"Westmeath":2,"Wexford":4,"Wicklow":2}
Any ideas?
It should be:
while($r = mysql_fetch_assoc($result)) {
$rows[$r['COUNTRY']] = $r['type'];
}
while($r = mysql_fetch_assoc($result)) {
$rows[] = $r;
}
Should be
while($r = mysql_fetch_assoc($result)) {
$rows[] = array($r['COUNTY'], $r['type']);
}

How to retrive php data from mysql and convert it to json?

My mind got stuck when i try to develope this:
i have a table in my database called "article" whit two column, "name" and "price".
How can i extract all rows from my table and echo all column in JSON?
i really can't understand how to convert result in JSON. My mind it's stuck like never before. i need to echo something like this:
{"items": {
"items":[
{"name": "firstitemname",
"price": "5"
},
{"name": "secondone",
"years": "3"
}],
}}
Please help me fixing my buggy code!
<?php
$query = mysql_query("SELECT * FROM itemlist");
$nameitem = array();
$itemprice = array();
while($row = mysql_fetch_array($query)){
array_push($nameitem , $row['nome']);
array_push($itemprice, $row['pix']);
}
?>
You would simply edit your PHP as follows.
<?php
$query = mysql_query("SELECT * FROM itemlist");
$items = array();
while($row = mysql_fetch_array($query)){
$items[] = array('name' => $row['nome'], 'price' => $row['pix']);
}
echo json_encode(array('items'=>$items));
?>
http://php.net/manual/en/function.json-encode.php
JSON is super easy to deal with in PHP.
If you're using PHP 5.2 or greater, you can use the json_encode function to do exactly what you're trying to do: http://www.php.net/manual/en/function.json-encode.php
For your code, you should be able to do something like this:
$query = mysql_query("SELECT * FROM itemlist");
$json_output = array();
while($row = mysql_fetch_assoc($query)){
$json_output[] = json_encode($row);
}
Here, $json_output will contain an array of strings with the json encoded string of each row as each array element. You can output these as you please.
<?php
$result = mysql_query("select * from item_list");
$rows = array();
while($r = mysql_fetch_assoc($result))
{
$rows[] = $r;
}
print json_encode($rows);
?>
Convert Data table to json with following code :
echo(json_encode($array));
for example ( select data from mysql and convert to json ):
public function SELECT($tableName,$conditions){
$connection = mysqli_connect($hostname, $userName, $password,$dbName);
try {
if (!$connection)
die("Connection failed: " . $connection->connect_error);
else
{
$qry = "";
if(!$this->IsNullOrEmptyString($conditions))
$qry = "SELECT * FROM `".$tableName."` WHERE ".$conditions;
else
$qry = "SELECT * FROM `".$tableName."`";
$result = mysqli_query( $connection, $qry);
if($result) {
$emparray = array();
while($row =mysqli_fetch_assoc($result))
$emparray[] = $row;
echo(json_encode($emparray));
}
else
echo(mysqli_error($connection));
}
mysqli_close($connection);
} catch(Exception $ex) {
mysqli_close($connection);
echo($ex->getMessage());
}
}

Categories