empty response php sql json - php

i am developing a php server sending arrays response to Android client using JSON. Now i simply testing the php code but the result is empty. Please help!!
<?php
#Connect to Database
$con = mysqli_connect("localhost","root","", "leoonline");
#Check connection
if (mysqli_connect_errno()) {
echo 'Database connection error: ' . mysqli_connect_error();
exit();
}
//Check already exist account
$allaccount = mysqli_query($con, "SELECT * FROM usersacc");
$results = array();
while($row = mysqli_fetch_array($allaccount))
{
$results[] = array(
'id' => base64_decode($row['id']),
'phone' => $row['phone'],
'password'> $row['password']
);
}
$json = json_encode($results);
?>

Is this your final code? You are not outputting anything apart from the connection error message if it happens.
Change
$json = json_encode($results);
to
echo json_encode($results);
If its still blank, then it could be a db data problem.

Related

PHP Script does not echo json encoded array

I have a php script which should echo a bunch of datasets in a json encoded string. Though the page is blank.
<?php
$con = mysqli_connect("SERVER", "USER", "PASSWORD", "DATABASE");
if(!$sql = "SELECT news.title, news.content, login.username, news.id, news.date, news.timestamp, news.importance, news.version FROM news INNER JOIN login ON news.id = login.id ORDER BY timestamp DESC") {
echo "FAIL";
}
mysqli_query($con,$sql);
$res = mysqli_query($con,$sql);
$result = array();
while($row = $res->fetch_array())
{
array_push($result,
array('title'=>$row[0],
'content'=>$row[1],
'author'=>$row[2],
'id'=>$row[3],
'date'=>$row[4],
'timestamp'=>$row[5],
'importance'=>$row[6],
'version'=>$row[7]
));
}
$oldjson = json_encode(["result"=>$result]);
echo json_encode(array("result"=>$result));
mysqli_close($con);
?>
What is the problem here? I tried some error detection with if(!..) but it did not help. I think the problem may be the array creation and/or echo, though I cannot figure out how to fix that.
You should check the result of json_encode, since you are encoding data that comes from the database you might have some stuff that requires escaping.
$json = json_encode(...);
if ($json === false) {
echo "Error = " . json_last_error() . " " . json_last_error_msg();
// You may want to var_dump the $result var here to figure out what the problem is
} else {
echo $json; // Should be ok
}

PHP : 'json_encode' from Database not showing any values

It's not a duplicate question about UTF-8 Unicode.
I am new to php and I am trying to create a json response.
I added data into my database properly as follows.
Then I tried to connect to DB and i did it successfully .
but after that when I tried to create a json response by using the following code, it doesn't shows any json response .
My PHP code is :
<?php
define('HOST','localhost');
define('USER','root');
define('PASS','qwerty');
define('DB','carol');
$con = mysqli_connect(HOST,USER,PASS,DB);
if (!$con)
{
echo "Please try later..";
}
else
{
echo "DB Connected..";
}
$sql = "SELECT * from songs";
$res = mysqli_query($con,$sql);
if (!$res)
{
echo "query failed..";
}
else
{
echo "Query success..";
echo (mysqli_num_rows($res));
}
$result = array();
while($row = mysqli_fetch_array($res)){
array_push($result,
array('title'=>$row[0]),
array('url'=>$row[1]),
array('lyrics'=>$row[2])
);
}
echo json_encode(array("result"=>$result));
mysqli_close($con);
?>
I'm getting only echo of DB Connected , Query Success and 14 (no of rows)
I'm trying PHP for the first time by using some online tutuorials.
if I did any mistake in my code,please help me to find my mistake.
Thank you in advance.
After I added echo var_dump($res);
I got

JSON ["data","pre database"]

So, I put my php page to connect to my android app on a hosted server (Hostgator). Now my PHP script for the JSON data seems to not be returning properly.This was working on my wamp server just fine. Example below of issue...
["data","pre database"][{"email":"thomas#wiregrass.edu","password":"test","fname":"Thomas","lname":"Cummings","phone":"5052030822","temppass":"15151","alert":"B"}]
Any ides as to what I did wrong or what is going on would be appreciated.
PHP script (might be outdated, this project is old):
<?php
$user = "ab73953_test";
$pass = "H3#ther78";
$db = "ab73953_testdb";
$out = array('data', 'pre database');
echo json_encode($out);
$db = mysqli_connect('localhost', $user, $pass, $db) or die("did not work");
$email=$_POST['username'];
$email = "thomas#wiregrass.edu"; // testing
$qry = 'SELECT * FROM users WHERE email = "'. $email .'"' ;
$result = mysqli_query($db, $qry) or die(" did not query");
$count = mysqli_num_rows($result);
$output = array();
if($count > 0){
while($row = mysqli_fetch_assoc($result))
{
$output[]=$row;
}
echo json_encode($output);
}
else
echo json_encode("Could not find user");
mysqli_close($db);
?>
That's not valid JSON. JSON is basically javascript: If the json you generate would be a javascript syntax error, then it's not valid json.
You have two separate echo json_encode(...) blocks, so you're producing two entirely separate/distinct json strings. Your output can only be one SINGLE json string.
e.g. [...][...] is two separate arrays that have gotten glued together. It's a javascript syntax error, therefore it's also invalid json. If you had something like
$arr1 = array(...);
$arr2 = array(...);
echo json_encode(array($arr1, $arr2));
you'd end up with
[[...],[...]]
and be ok
But you have
echo json_encode($arr1);
echo json_encode($arr2);
and end up with
[...][...]
which is an outright syntax error.
And note that you're vulnerable to sql injection attacks.

Load mysql data to Highcharts line chart using JSON

I'm trying to import my data from a database to a line chart (Highcharts). My code doesn't work.
Here is my PHP code:
<?php
require('../php/config.php');
$con=mysqli_connect("localhost", "root", "ginnastica", "progetto");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
if(isset($_GET['src']))
{
$records=array();
$records = select($mysqli,"SELECT Sesso AS name, Occupati AS data FROM occupazione WHERE Sesso='totale' AND Periodo LIKE '%2008'");
$rows = array();
$rows['name'] = 'Totale';
while($r = mysql_fetch_assoc($records)) {
$rows['data'][]=$r['data'];
}
return json_encode($rows);
}
else
return json_encode(array('status' => 'error', 'details' => 'no src provided'));
}
?>
It seems that "mysql_fetch_assoc" doesn't work. The output of my array $rows id that:
{
"name": "Totale"
}
There isn't an element called "data".
What am I doing wrong?
At first:
It would be worth to see what is in your ../php/config.php file, because the content of that file may impact the behavior of other lines you provided.
The structure and data (at least few lines of data) of occupazione table is also worth to see, because data or structure could change the output as well.
You are missing a { after the else, - as #Moppo already mentioned.
Warning on mysql_fetch_assoc
This extension is deprecated as of PHP 5.5.0, and will be removed in the future. Instead, the MySQLi or PDO_MySQL extension should be used. Read more in php.net
After that and some more fixes I would finally write your code in the way close to that:
<?php
$con = mysqli_connect("localhost", "root", "ginnastica", "progetto");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
if (isset($_GET['src'])) {
$records = $con->query("SELECT Sesso AS name, Occupati AS data FROM occupazione WHERE Sesso='totale' AND Periodo LIKE '%2008'");
$rows = array();
$rows['name'] = 'Totale';
while ($r = $records->fetch_assoc()) {
$rows['data'][] = $r['data'];
}
return json_encode($rows, JSON_NUMERIC_CHECK);
} else {
return json_encode(array('status' => 'error', 'details' => 'no src provided'));
}
As I said, we know nothing about database you work with, so my guess would be that your select returns no lines as a result. And then you got no data (only {"name": "Totale"}), just because while has nothing to iterate throw.

JSON returns [null,null] in my app

I want to send database records with a PHPH file via json to my app I am making with IntelXDK. Because I can't use PHP code with the Intel XDK, I needed to use JSON. I want to show the two records 'quote' and 'author' from my 'quotes' table on my screen. Someone helped me to this code but it just returns [null,null]instead of the two records I need.. I tried debugging but I am new to PHP so I can'get it to work.. Anyone who can help or sees an error in this code? Thanks!
PS: Yes I now there are already multiple questions asked on this subject by other people. I have read them all but none of them solves my question..
<?php
if(isset($_GET["get_rows"]))
{
//checks the format client wants
if($_GET["get_rows"] == "json")
{
$link = mysqli_connect("localhost", "xxxxx", "xxxxx", "xxxx");
/* check connection */
if (mysqli_connect_errno()) {
echo mysqli_connect_error();
header("HTTP/1.0 500 Internal Server Error");
exit();
}
$query = "SELECT quote, author FROM quotes WHERE id = " . date('d');
$jsonData = array();
if ($result = mysqli_query($link, $query)) {
/* fetch associative array */
$row = $result->fetch_assoc($result);
// Create a new array and assign the column values to it
// You can either turn an associative array or basic array
$ret= array();
$ret[] = $row['quote'];
$ret[] = $row['author'];
//encode to JSON format
echo json_encode($ret);
}
else {
echo json_encode($ret);
}
/* close connection */
mysqli_close($link);
}
else
{
header("HTTP/1.0 404 Not Found");
}
}
else
{
header("HTTP/1.0 404 Not Found");
}
?>
You have a bug in fetch_assoc() function call - remove $result parameter. If you had error reporting enabling, you should see:
Warning: mysqli_result::fetch_assoc() expects exactly 0 parameters, 1 given
Just change it to:
$row = $result->fetch_assoc();
In javascript to parse this response, just do this:
var obj = JSON.parse(xmlhttp.responseText);
document.getElementById("quote").innerHTML = obj[0];
document.getElementById("author").innerHTML = obj[1];
I think your problem is with fetch_assoc()
Try to use that :
$row = mysqli_fetch_assoc($result);
instead of
$row = $result->fetch_assoc($result);
It's works for me with your example
change this
$row = $result->fetch_assoc($result);
to
$row = $result->fetch_assoc();
Just change it to:
$row = $result->fetch_assoc();
Updated:
response = JSON.parse(xmlhttp.responseText);
you can now access them independently as:
reponse.quote and response.author

Categories