getting data from database as a json response - php

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

Related

review system with function in variable

so basically I am trying to create a little thing where it outputs stars, based on the database saved rating integer. The problem is it does not seem to put the number I from the database, in the variable. Here is the code I used:
<?php
$productID = 100;
$con = mysqli_connect("localhost", "root", "", "example");
function connect()
{
$con = mysqli_connect("localhost", "root", "", "example");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
} else {
return $con;
}
}
function getStars($con)
{
$productID = 100;
$sql = "SELECT rating
FROM reviews
-- JOIN stockitemstockgroups USING (StockItemID)
-- JOIN stockgroups USING (StockGroupID)
WHERE reviewID = '5'
";
$result = $con->query($sql);
if ($con && ($result->num_rows > 0)) {
// output data of each row
while ($row = $result->fetch_assoc()) {
echo $row["rating"];
}
} else {
echo "error";
}
}
$value = getStars($con);
echo $value;
for ($x = 1; $x <= $value; $x++) {
echo '<div class="rating"><span>★</span></div>';
}
?>
I'm having trouble finding a duplicate, though I'm sure this is one. You aren't returning anything from your function, so $value doesn't have a value.
function getStars($con)
{
$productID = 100;
$sql = "SELECT rating FROM reviews WHERE reviewID = 5";
$result = $con->query($sql);
if ($result && ($result->num_rows > 0)) {
// output data of first row
$row = $result->fetch_assoc();
return $row["rating"];
} else {
return false;
}
}
As a general rule, never echo from a function. Also, no need for a loop over what will presumably be a single result.

PHP - Insert Value with Key from another array into Array in Specific Place

I am trying to create a JSON object as an array from the data received from the SQL Query. Currently the encoded JSON I have got is:
[{"firstname":"Student","lastname":"1"},{"firstname":"Student","lastname":"2"},{"firstname":"Student","lastname":"3"}]
The values I want to insert from another array, the values are in corresponding order to the each array in the JSON above: (JSON)
["85.00000","50.00000","90.00000"]
So the JSON should look like:
{"firstname":"Student","lastname":"1","grade":"85.00000"}
My Current Code:
//Provisional Array Setup for Grades
$grade = array();
$userid = array();
$sqldata = array();
foreach($json_d->assignments[0]->grades as $gradeInfo) {
$grade[] = $gradeInfo->grade;
$userid[] = $gradeInfo->userid;
}
//Server Details
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "moodle";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
foreach($userid as $id) {
$sql = "SELECT firstname, lastname FROM mdl_user WHERE id='$id'";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
// output data of each row
while($row = mysqli_fetch_array($result, MYSQL_ASSOC)) {
$sqldata[] = $row;
}
} else {
echo "ERROR!";
}
}
$sqlr = json_encode($sqldata);
$grd = json_encode($grade);
echo $sqlr;
echo $grd;
mysqli_close($conn);
try this code:
foreach($userid as $x => $id) {
$sql = "SELECT firstname, lastname FROM mdl_user WHERE id='$id'";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
// output data of each row
while($row = mysqli_fetch_array($result, MYSQL_ASSOC)) {
$row['grade'] = $grade[$x];
$sqldata[] = $row;
}
} else {
echo "ERROR!";
}
}
I added the Variable $x and added $row['grade'] with the same index on the $gradearray
function set_column_values($arr, $column_name, $column_values) {
$ret_arr = array_map(function($arr_value, $col_value) use ($column_name) {
$arr_value[$column_name] = $col_value;
return $arr_value;
}, $arr, $column_values);
return $ret_arr;
}
$sqldata = set_column_values($sqldata, 'grades', $grade);
$sqlr = json_encode($sqldata);
var_dump($sqlr);
Hope it helps!

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);
?>

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

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.

Categories