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);
}
}
?>
Related
When I run the following code In PHP
$connect = mysqli_connect("localhost", "root", "dbpass", "db");
function csvfromarray($array) {
$result = $array[0]+","+$array[1];
return $result;
}
$query = mysqli_query($connect, "SELECT * FROM dbtable");
$row = mysqli_fetch_assoc($query);
$data = array();
$i = 0;
while($row = mysqli_fetch_assoc($query)) {
$data[$i] = $row['last'];
$i++;
}
$csv = csvfromarray($data);
echo $csv;
mysqli_close();
I end up getting an echoed response of "0" when I should be returning "lname1,lname2".
All of chris85's stuff is correct...
Here's a tidy up:
$query=mysqli_query($connect,"SELECT `last` FROM dbtable");
$data=array();
while($row=mysqli_fetch_assoc($query)) {
$data[]=$row['last']; // push into array
}
echo implode(',',$data); // echo comma-separated values
mysqli_close();
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);
?>
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.
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.
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);
?>