PHP json_encode doesn't print anything - php

I'm running PHP and MySQL and have the following code:
$data = array();
$result = mysql_query($search_query);
if ($result){
while($row = mysql_fetch_assoc($result)) {
$data[] = $row;
}
if (sizeof($data) > 0) {
//var_dump($data);
echo json_encode($data);
} else {
echo 'empty';
}
}
If my query has no rows I do get empty returned.
But if there's any records I get a Resource has no content in Safari.
But if I uncomment my //var_dump($data); then I do get a nice array of values.

Try this:
// Database connection.
$mysqli = new mysqli('localhost', 'user', 'password', 'db_name');
// Your query.
$search_query = "SELECT * FROM yuor_table";
$data = array();
$result = $mysqli->query($search_query);
if ($result){
while($row = $result->fetch_assoc()) {
$data[] = $row;
}
if (sizeof($data) > 0) {
//var_dump($data);
echo json_encode($data);
} else {
echo 'empty';
}
}
This is very simple solution. I would suggest to use "mysqli".

Related

How to format a json response in php

I am new to php and am trying to return a json response in a particular structure. Here is what I have tried so far:
$response = array();
if ($con) {
$sql = "select * from admission_view";
$result = mysqli_query($con, $sql);
if ($result) {
$x = 0;
while ($row = mysqli_fetch_assoc($result)) {
$response[$x]['id'] = $row['id'];
$response[$x]['name'] = $row['name'];
$response[$x]['isActive'] = $row['isActive'];
$response[$x]['branchId'] = $row['branchId'];
$response[$x]['branch'] = $row['branch'];
$response[$x]['customerGroupId'] = $row['customerGroupId'];
$response[$x]['customerGroup'] = $row['customerGroup'];
$response[$x]['orderNo'] = $row['orderNo'];
$x++;
}
echo json_encode($response, JSON_PRETTY_PRINT);
}
} else {
echo "Connection error";
}
The code above returns this response:
However, instead of returning for example "branchId" and "branch" as individual properties, I want to pass their values inside a branchObject such that branch.id == "branchId" and branch.name == "branch".I mean, How may I return the response in the following structure:
And Here is how my database looks like:
How can I achieve this?
You ask for stuff that we are unsure if db result returns but as nice_dev pointed out, you need something like this:
$response = [];
if ($con) {
$sql = "select * from admission_view";
$result = mysqli_query($con, $sql);
if ($result) {
$x = 0;
while ($row = mysqli_fetch_assoc($result)) {
$response[$x]['id'] = $row['id'];
$response[$x]['name'] = $row['name'];
$response[$x]['isActive'] = $row['isActive'];
$response[$x]['branch']['id'] = $row['branchId'];
$response[$x]['branch']['name'] = $row['branch'];
$response[$x]['customerGroup']['id'] = $row['customerGroupId'];
$response[$x]['customerGroup']['name'] = $row['customerGroup'];
$response[$x]['customerGroup']['orderNo'] = $row['orderNo'];
$x++;
}
echo json_encode($response, JSON_PRETTY_PRINT);
}
} else {
echo "Connection error";
}

how to display in json format using 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);
?>

how form array in do-while?

I try to form array in the do-while:
$result = mysql_query("SELECT * FROM data WHERE company='$companyID'", $db);
if (mysql_num_rows($result) > 0)
{
$resultData = mysql_fetch_array($result);
do
{
$json[] = array('product' => $resultData['product'], 'title' => $resultData['title']);
}
while($resultData = mysql_fetch_array($result));
echo json_encode($json);
}
In exit all datais empty(error):
"[{"product":"","title":""},{"product":"","title":""},{"product":"","title":""},{"product":"","title":""}]"
does it actually give you an error?
try printing out your output to see if you actually fetch anything from mysql
$result = mysql_query("SELECT * FROM data WHERE company='".$companyID."'", $db);
if (mysql_num_rows($result) > 0)
{
while($resultData = mysql_fetch_array($result))
{
echo '<pre>';
print_r($resultData);
echo '</pre>';
}
}
if you do get output that way just replace the content between {} of while with echo json_encode($json);
hope this helps.

mysqli query only returning first row

I am migrating from mysql to mysqli, and I am having trouble returning more than one row from the database in a query.
$db = new mysqli($hostname, $sql_us, $sql_us_pwd, $sql_db); // This is already connected
function db_query($db, $query, $type = 'object') {
global $db;
$result = $db->query($query);
if ($type == 'assoc') {
while($row = $result->fetch_assoc()) {
return $row;
}
} else {
while($row = $result->fetch_object()) {
return $row;
}
}
mysqli_free_result($result);
}
$query = "SELECT * FROM `users`";
$user = db_query($db, $query);
print_r($user); // This is only returning the first row of results
I'm obviously trying to make a function where I can query the database and either return the results in an associative array or as an object. What am I doing wrong?
Use this code:
$rows = array();
if ($type == 'assoc') {
while($row = $result->fetch_assoc()) {
$rows[] = $row;
}
} else {
while($row = $result->fetch_object()) {
$rows[] = $row;
}
}
return $rows;
You are using the return inside the while and return terminates the while loop after first iteration that's why you are getting only one row.
You need to store while loop values into array try this
$rows = array();
if ($type == 'assoc') {
while($row = $result->fetch_assoc()) {
$rows[] = $row;
}
} else {
while($row = $result->fetch_object()) {
$rows[] = $row;
}
}
return $rows;
When you return in a function it stops executing at that point and goes back to the where it was called from with the value that you are returning.
In your case when you do a return $row, you are getting out of the function as soon as the first row is read.
Fix is:
$result = array();
if ($type == 'assoc') {
while($row = $result->fetch_assoc()) {
$result[] = $row;
}
} else {
while($row = $result->fetch_object()) {
$result[] = $row;
}
}
return $row;
You are only returning the first row. You have to return an array.
$arr = array();
if ($type == 'assoc') {
while($row = $result->fetch_assoc()) {
$arr[] = $row;
}
}
else {
while($row = $result->fetch_object()) {
$arr[] = $row;
}
}
return $arr;

Return results from mysql, using user functions

Please tell, why this code is wrong?
function myres () {
$db = new mysqli("localhost","userrr","pass","mvc");
$res = $db->query("SELECT * FROM news ");
return $res;
}
while ($row = myres()->fetch_row()) {
echo $row[0];
}
P.S.
this code is working:
$db = new mysqli("localhost","userrr","pass","mvc");
$res = $db->query("SELECT * FROM news ");
while ($row = $res->fetch_row()) {
echo $row[0];
}
Here you call myres() every time, I think:
while ($row = myres()->fetch_row()) {
echo $row[0];
}
So every time $row contain first row of the result, and it will not stop. It will works fine, I think:
$res = myres();
while ($row = $res->fetch_row()) {
echo $row[0];
}

Categories