how to display in json format using php - php

using php database connection i want to display data in json format which data are fatched from database(MySql),but i can't displaying in json format. http://takeyourtime.16mb.com/fatchData.php
$con = mysqli_connect($host, $username, $pwd, $db) or die('Unable to connect');
if (mysqli_connect_error($con))
{
echo "Failed to Connect to Database ".mysqli_connect_error();
}
$name = $_POST['Query'];
$sql = "SELECT * FROM playerstb";
$query = mysqli_query($con,$sql);
if ($query)
{
$rows = array();
while ($r = mysql_fetch_assoc($query)) {
$rows['root_name'] = $r;
}
}
echo json_encode($rows);
mysqli_close($con);

Just use json_encode. BTW, your script has an syntax error in the ending if block:
if($query){
$rows = array();
while($r = mysql_fetch_assoc($query)) {
$rows['root_name'][] = $r; // probably must be an array
}
echo json_encode($rows);
}else{
/*
This will show up when you have a query error
nothing to do with the results found.
I would consider changing the message below
*/
echo('Not Found');
}

inside your while loop you dont save all results you each one writen over the before one
you have to store it in array like note this ([])*
while($r = mysql_fetch_assoc($query)) {
$root_names[] = $r;
}
echo json_encode(['root_name'=>$root_names]);

You have to store first your result in array then after that create an array name your desire key ($array["name"])
$con=mysqli_connect($host,$username,$pwd,$db) or die('Unable to connect');
if(mysqli_connect_error($con))
{
echo "Failed to Connect to Database ".mysqli_connect_error();
}
$name=$_POST['Query'];
$sql="SELECT * FROM playerstb";
$query=mysqli_query($con,$sql);
if($query)
{
$rows = array();
while($r = mysql_fetch_assoc($query)) {
$rows[] = $r;
}
$data["data"]=$rows;
echo json_encode($data);
}
}else
{
echo('Not Found ');
}
mysqli_close($con);
?>

Related

returning null array from php file

i am sending a value from my android app (value) using
httpClient, i need to fetch a row from DB according to that value, when i try it
it returns a null array (json array), but if i use static value like name, for
example:
$result = mysql_query("SELECT * FROM table WHERE column= 'name'");
i get the array successfully, here is the php file, please help
<?php
$con = mysql_connect("localhost","user","pass");
if (!$con) {
die("Could not connected".mysql_error());
} else {
mysql_select_db("database",$con);
if (!empty($_POST['value'])) {
$value=$_POST['value'];
$result = mysql_query("SELECT * FROM table WHERE column= '$value'");
while ($row = mysql_fetch_assoc($result)) {
$output[]=$row;
}
print(json_encode($output));
mysql_close($con);
}
}
?>
Try this:
$output = array();
$i=0;
while($row = mysql_fetch_assoc($result))
{
$output[$i]=$row;
$i++;
}
print(json_encode($output));
You have to create array before while loop as following.
$output = array();
Following is your correct code, I am assuming that you are getting value in your post variable.
<?php
$con = mysql_connect("localhost","user","pass");
if(!$con)
{
die("Could not connected".mysql_error());
}
else
{
mysql_select_db("database",$con);
if(!empty($_POST['value']))
{
$value=$_POST['value'];
$result = mysql_query("SELECT * FROM table WHERE column= '$value'");
$output = array();
while($row = mysql_fetch_assoc($result))
{
$output[]=$row;
}
print(json_encode($output));
mysql_close($con);
}
}
?>

Php MySQL into json - trying to put query into function

I'm trying to build a very basic API, I've got a query that pulls data from a MySQL view, I can echo the query out as json no problem but I want to put the query in a function in order to be able to call it from the API script...I'm just having some trouble putting the code into a function.
Here's the ode that works.....
<?php
$servername = "database.com";
$username = "username";
$password = "password";
$dbname = "db1";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT * from DB_Available_Dates";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo $row["year"]. " - " . $row["Month"]. " " . $row["the_days"]. "<br>";
}
} else {
echo "0 results";
}
$conn->close();
?>
...and this is my attempt to put it into a function (that doesn't work!)...
//Connection as above
function available_dates() {
$sql = "SELECT * from DB_Available_Dates";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
$encodeArray = array();
while($row = $result->fetch_assoc()) {
$encodeArray[] = $row;
}
} else {
echo "0 results";
}
$dates = array();
$dates = json_encode($encodeArray);
return $dates;
}
available_dates();
$conn->close();
?>
I've just started with functions so I expect my errors to be quite comical!
...do I need to use echo to call the function?
you are not returning anything,you should assign return value to some thing.You should call your function like this.
function available_dates() {
$sql = "SELECT * from DB_Available_Dates";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
$encodeArray = array();
while($row = $result->fetch_assoc()) {
$encodeArray[] = $row;
}
} else {
echo "0 results";
}
$dates = array();
$dates = json_encode($encodeArray);
return $dates;
}
$result=available_dates();
You are doing nothing with the return value of your function.
You can echo it or put it in a variable.
echo available_dates();
or
print_r(available_dates());
or
$results = available_dates();
You're returning an array in your code:
$dates = array();
$dates = json_encode($encodeArray);
return $dates;
You should simply echo the json_encode like this:
echo json_encode($encodeArray);
And then take care of the formatting/displaying (alternatively, you could do it like in your first example and echo back the output ready for displaying):
while($row = $result->fetch_assoc()) {
$encodeArray[] = $row["year"]. " - " . $row["Month"]. " " . row["the_days"].<br>";
}
and then
echo json_encode($encodeArray);

JSON Array of objects with MySql

i am trying to get this output from a database of countries. i had use the mysqli_fetch_object() function but it does not work with me
"countries":[{"countryname":"India","flag":"http:\/\/wptrafficanalyzer.in\/p\/demo1\/india.png","language":"Hindi","capital":"New Delhi","currency":{"code":"INR","currencyname":"Rupee"}},{"countryname":"Pakistan","flag":"http:\/\/wptrafficanalyzer.in\/p\/demo1\/pakistan.png","language":"Urdu","capital":"Islamabad","currency":{"code":"PKR","currencyname":"Pakistani Rupee"}}]}
and i am use this php script
<?php
require 'config.php';
$con=mysqli_connect($servername,$username,$password,$db);
if(!$con)
{
die ("Erro in connection" . mysqli_connect_error);
}
else{ $encode = array();
$sql="select * from country ";
$res=mysqli_query($con,$sql);
if(mysqli_num_rows($res)>0)
{
$temp_array=array();
while($row=mysqli_fetch_object($res))
{
//$temp_array[]=$row;
$encode=$row;
}
//echo json_encode($temp_array);
echo json_encode($encode);
}
else
{
echo " 0 Rows";
}
}
?>
if anybody can help me ?
Your code should be something like below;
<?PHP
require 'config.php';
$con=mysqli_connect($servername,$username,$password,$db);
if(!$con)
die ("Error in connection" . mysqli_connect_error);
else{
$encode = array();
$sql = "select * from country ";
$res = mysqli_query($con,$sql);
if(mysqli_num_rows($res)>0)
{
$temp_array=array();
while($row=mysqli_fetch_object($res))
{
$encode[]=$row;
}
}
echo json_encode($encode);
}
?>
You do not need to write down 0 rows because you are returning a json object which has an array so when you check result.length it tells you the row count.
As an advice you may use something like below;
<?php
require 'config.php';
$con = mysqli_connect($servername,$username,$password,$db);
$resultArray = array();
$resultArray["error"] = true; //That will tell your javascript client if any error exits.
$resultArray["errorMessage"] = ""; //We will set this value if any error exits;
if(!$con)
{
$resultArray["error"] = true;
$resultArray["errorMessage"] = "Error in connection" . mysqli_connect_error();
}
else{
$resultArray["error"] = false;
$itemCollection = array();
$sql = "select * from country ";
$res = mysqli_query($con,$sql);
if(mysqli_num_rows($res)>0)
while($row = mysqli_fetch_object($res))
$itemCollection[]=$row;
$resultArray["itemCollection"] = $itemCollection;
}
echo json_encode($resultArray);
?>
In my sample you are going to get a json result something like below;
{"error":true,"errorMessage":"ErrorMessageIfExists","itemCollection":[yourObject,yourObject]}
Hope this helps you.

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.

getting data from database as a json response

Here I am trying to get some data from database and want to display it as a json response so that user can fetch each field.
Here is how user can perform query
http://localhost/safari/index.php?getbranch=true
this should give branch details from tables.
Here is PHP code to do it
<?php
if(isset($_GET['getbranch']))
{
$getbranch = $_GET['getbranch'];
if($getbranch == 'true')
{
getbranch($getbranch);
}
}
function getbranch($getbranch)
{
$con = mysqli_connect('127.0.0.1', 'root', '', 'safari');
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
return;
}
$today = date("Ymd");
$result = mysqli_query($con,"SELECT division, branch,branchofficename,branchofficecode,status from tbl_branchoffice");
while ($row = #mysqli_fetch_array($result))
{
$result1 = json_encode($row);
}
echo $result1;
}
What's wrong wit this?
JSON response:
[{"0":"3","sno":"3","1":"2","division":"2","2":"2","branch":"2","3":"SAFFARI TRAVELS","branchofficename":"SAFFARI TRAVELS","4":"gfgbhghfhf","branchofficecode":"gfgbhghfhf","5":"active","status":"active"},
{"0":"4","sno":"4","1":"2","division":"2","2":"chennai","branch":"chennai","3":"chennai","branchofficename":"chennai","4":"br01","branchofficecode":"br01","5":"active","status":"active"},{"0":"5","sno":"5","1":"3","division":"3","2":"delhi","branch":"delhi","3":"delhi","branchofficename":"delhi","4":"br02","branchofficecode":"br02","5":"notactive","status":"notactive"},{"0":"6","sno":"6","1":"2","division":"2","2":"bangalore","branch":"bangalore","3":"bangalore","branchofficename":"bangalore","4":"br03","branchofficecode":"br03","5":"active","status":"active"},{"0":"7","sno":"7","1":"3","division":"3","2":"pune","branch":"pune","3":"pune","branchofficename":"pune","4":"br04","branchofficecode":"br04","5":"notactive","status":"notactive"}]
Change your while loop
$result1 = array();
while ($row = #mysqli_fetch_array($result))
{
array_push($result1 , $row);
}
by doing so, you have collected all result in $result1
now you can encode it
echo $result1 = json_encode( $result1);
I will prefer to use array, ignor json_encode line code,
foreach($result1 as $resultset){
//resultset contains one single row of table
foreach($resultset as $column => $columnValue){
//assuming your table column name as 'city'
if($column == 'city' && $columnValue == 'pune' ){
//displaying array of table which satisfies the condition
var_dump($resultset );
}
}
}
$result1 = array();
if(isset($_GET['getbranch']))
{
$getbranch = $_GET['getbranch'];
if($getbranch == 'true')
{
getbranch($getbranch);
}
}
function getbranch($getbranch)
{
$con = mysqli_connect('127.0.0.1', 'root', '', 'safari');
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
return;
}
$today = date("Ymd");
$result = mysqli_query($con,"SELECT division,
branch,branchofficename,branchofficecode,status from tbl_branchoffice");
while ($row = #mysqli_fetch_array($result))
{
$result1[] = $row;
}
echo json_encode($result1);
}
First collect each row from the result into the array result1 and then finally output the json_encode of $result1 array

Categories