make json array from mysql data using php - 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);
?>

Related

while ($data = mysql_fetch_array() ) doesnot working

I'm trying to get data from mysql and show them using while loop. But problem is inside while loop there is always one less data i'm getting.
Suppose there is two row in my db , but using this code i'm getting only one row. First row always missing. Cant figure out why ! Sharing some of the code.
tried var_dump() , it shows there is right number rows in db
$ddaa = mysql_query("SELECT * FROM coupons ORDER BY id");
echo mysql_error();
$data = mysql_fetch_array($ddaa);
while ($data = mysql_fetch_array($ddaa))
{
echo $data['id'] ;
}
You are fetching one row before using while loop which you are not using anywhere, thats why you are loosing one row.
$ddaa = mysql_query("SELECT * FROM coupons ORDER BY id") or die(mysql_error());
while ($data = mysql_fetch_array($ddaa))
{
echo $data['id'] ;
}
Try to remove this line:
$data = mysql_fetch_array($ddaa);
The server and database credentials are missing in your code try this one
$server = 'server_name';
$user = 'server_username';
$pass = 'server_password';
$db = 'database_name';
$connection = new mysqli($server, $user, $pass, $db);
$aa = "SELECT * FROM coupons ORDER BY id";
$dd = mysqli_query($connection,$aa); // $connection is the variable which contains server and database credentials;
while ($data = mysqli_fetch_assoc($dd)) {
echo $data['id'];
}
It Will Work For Me. Try This...
<?php
$con=mysql_connect('localhost','root','') or die("could not connect".mysql_error());
mysql_select_db('dbname');
$query = mysql_query("SELECT * FROM Student");
$num_rows = mysql_num_rows($query);
while($row = mysql_fetch_array($query))
{
echo $row['firstname'];
}
echo "<h3>Record Selected successfully\n</h3>";
mysql_close($con);
?>

how to solve anonymous array?

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.

Get an array of JSON data from php database

I am kinda new to SQL and I am having a problem. I am following the tutorial from Here to try to get data from my database into my android app.
I have it working, but it only gets one line. I know it should be possible to iterate through the database and echo out every line that matches the ID to JSON, but I do not know how. How would I do this?
My current code:
<?php
if($_SERVER['REQUEST_METHOD']=='GET'){
$id = $_GET['id'];
require_once('dbConnect.php');
$sql = "SELECT * FROM LATLON WHERE DeviceID='".$id."'";
$r = mysqli_query($con,$sql);
$res = mysqli_fetch_array($r);
$result = array();
array_push($result,array(
"INDEX"=>$res['INDEX'],
"DeviceID"=>$res['DeviceID'],
"LAT"=>$res['LAT'],
"LON"=>$res['LON']
)
);
echo json_encode(array("result"=>$result));
mysqli_close($con);
}
?>
EDIT
I edited my code to this, but I am getting nothing. Still not quite understanding what is happening. Thanks for all the help!
<?php
if($_SERVER['REQUEST_METHOD']=='GET'){
$id = $_GET['id'];
require_once('dbConnect.php');
$sql = "SELECT * FROM LATLON WHERE DeviceID='".$id."'";
$r = mysqli_query($con,$sql);
while($row = $result->mysqli_fetch_array($r, MYSQLI_ASSOC)){
$array[] = $row;
}
echo json_encode($array);
mysqli_close($con);
}
?>
You can iterate through mysqli_fetch_array();
while($row = mysqli_fetch_array($r, MYSQLI_ASSOC)) {
$array[] = $row;
}
echo json_encode($array);
When you use the OO interface, the method names don't begin with mysqli_, that's only used for procedural calls. You also have no variable named $result, the result is in $r.
So it should be:
while ($row = $r->fetch_array(MYSQLI_ASSOC)) {
or:
while ($row = mysqli_fetch_array($r, MYSQLI_ASSOC)) {

Unable to get the records from php script to android app

I am using android volley library to get the records from database on server. I send a query from my android app to this php script. When I write query myself in 4th line as follows $myquery = "Select firstname from Student;"; then all results are returned correctly but when I send a query directly, it doesn't returns records. I am sure that the issue is in php script, please help me where I am going wrong in this basic script?
function showStudent()
{
global $connect;
$myquery = $_POST["query"];
$result = mysqli_query($connect,$myquery);
$number_of_rows = mysqli_num_rows($result);
$temp_array = array();
if($number_of_rows>0)
{
while( $row = mysqli_fetch_assoc($result) )
{
$temp_array[] = $row;
}
}
header('Content-Type: application/json');
echo json_encode(array("dataArray"=>$temp_array));
mysqli_close($connect);
}
?>
Change to this
$myquery = $_REQUEST['query'];
Instead of this
$myquery = $_POST["query"];

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.

Categories