php jsonparsing error no data on browser - php

<?php
$con = mysqli_connect("localhost", "alsmwsk3", "skrktkzl12", "alsmwsk3");
$result = mysqli_query($con, "select * from NOTICE ORDER BY noticeDate DESC");
$response = array();
$num = 0;
while($row = mysqli_fetch_array($result))
{
array_push($response, array("noticeContent"=>$row[0],"noticeName"=>$row[1],"noticeDate"=>$row[2]));
echo $num;
}
//php를 읽었을떄 json타입이 아닐 readed php not but json?
//print (json_encode($response));
// echo json_encode(array("response"));
echo json_encode(array("response"=>$response));
mysqli_close($con);
?>
when I open this phpsource on browser there are no data on browser I think am i wrong some kind of miss?
and it is mysql setting

Related

Return result from php to json file

I have created API from my DB and the result appears in a PHP file, so the question is how I can read this result in a .json file?
<?php
$con = mysqli_connect("localhost","root","Password##","Mydb");
$response = array();
if($con){
$sql = "select * from limit_order";
$result = mysqli_query($con,$sql);
if($result){
header("Content-Type: JSON");
$i=0;
while($row = mysqli_fetch_assoc($result)){
$response[$i]['order_type'] = $row ['order_type'];
$response[$i]['from'] = $row ['from'];
$response[$i]['to'] = $row ['to'];
$response[$i]['quantity'] = $row ['quantity'];
$response[$i]['limit_price'] = $row ['limit_price'];
$response[$i]['created_at'] = $row ['created_at'];
$response[$i]['updated_at'] = $row ['updated_at'];
$response[$i]['status'] = $row ['status'];
$i++;
}
echo json_encode($response,JSON_PRETTY_PRINT);
}
}
else{
echo "Database connection failed";
}
?>

PHP JSON not displaying MySQL result

The PHP I created retrieve data from a MySQL database and turns it into a JSON which is then echoed. I had 300 records and the PHP was able to display the JSON and was visible when viewed.
However, I added another 100 records to the same table and for some reason the JSON isn't being displayed. It just appears blank with no error. But when I remove the 100 records, the JSON displays as normal.
I haven't touched the PHP file during this. What could the reason be?
<?PHP
include_once("connection.php");
$query = "select id,mosque_name,latitude,longitude from mosques;";
$result = mysqli_query($conn, $query);
if (mysqli_num_rows($result) > 0) {
$response["mosques"] = array();
while ($row = mysqli_fetch_array($result)) {
$mosque = array();
$mosque["id"] = $row["id"];
$mosque["mosque_name"] = $row["mosque_name"];
$mosque["latitude"] = $row["latitude"];
$mosque["longitude"] = $row["longitude"];
array_push($response["mosques"], $mosque);
}
$response["success"] = 1;
// echoing JSON response
echo json_encode($response);
} else {
$response["success"] = 0;
$response["message"] = "No mosques found";
echo json_encode($response);
}
?>
Try This:-
<?PHP
include_once("connection.php");
$query = "select id,mosque_name,latitude,longitude from mosques;";
$result = mysqli_query($conn, $query);
if (mysqli_num_rows($result) == 0) {
echo json_encode("");
}
else{
while ($row = mysqli_fetch_array($result)) {
/*$mosque = array();
$mosque["id"] = $row["id"];
$mosque["mosque_name"] = $row["mosque_name"];
$mosque["latitude"] = $row["latitude"];
$mosque["longitude"] = $row["longitude"];*/
$fetchRow[]=$row;
// array_push($response["mosques"], $mosque);
}
echo json_encode($fetchRow);
}
/* $response["success"] = 1;
echoing JSON response
echo json_encode($response);*/
?>
and check your result from network

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)) {

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.

json formatting_adding a tag to it

here is the PHP file that im using to generate the JSON with:
<?
$databasehost = "wbw.com";
$databasename = "wtest";
$databaseusername ="w";
$databasepassword = "123";
$query = "SELECT * FROM `and` LIMIT 0 , 30";
$con = mysql_connect($databasehost,$databaseusername,$databasepassword) or die(mysql_error());
mysql_select_db($databasename) or die(mysql_error());
$sth = mysql_query($query);
if (mysql_errno()) {
header("HTTP/1.1 500 Internal Server Error");
echo $query.'\n';
echo mysql_error();
}
else
{
$rows = array();
while($r = mysql_fetch_assoc($sth)) {
$rows[] = $r;
}
print json_encode($rows);
}
?>
The problem with it is that it generates a result like this:
[{"Reg_user_name":"nn","Username":"ns","Device
Code":"2366c84dead","HTTP":"https://api.ee.com/v1//306ad73427e262r9","Device
Name":"office"},{"Reg_user_name":"nn","Username":"nn","Device
Code":"2366c84dead","HTTP":"https://api.ee.com/v1/e/306ad73427e262e7","Device
Name":"LAB lighting"}]
BUT in order to use the JSONobject and get the elements in it I need to give JSON like follows:
["Information":{"Reg_user_name":"nn","Username":"ns","Device
Code":"2366c84dead","HTTP":"https://api.ee.com/v1//306ad73427e262r9","Device
Name":"office"},{"Reg_user_name":"nn","Username":"nn","Device
Code":"2366c84dead","HTTP":"https://api.ee.com/v1/e/306ad73427e262e7","Device
Name":"LAB lighting"}]
I want to know that what I have to add in the PHP file to get that data with the added "information:" tag to it automatically using the above PHP file.
If you only want one index, you can change this
$rows = array();
while($r = mysql_fetch_assoc($sth)) {
$rows[] = $r;
}
print json_encode($rows);
into this
$rows = array();
while($r = mysql_fetch_assoc($sth)) {
$rows[] = $r;
}
$json = array(
'information' => $rows,
);
print json_encode($json);
just add string index to the array the json encoder will automatically convert it
check this
while($r = mysql_fetch_assoc($sth))
{
$rows['information'][] = $r;
}
echo json_encode($rows);

Categories