exporting data in json format - php

I am trying to export data from PhpMyAdmin to JSON format
This code works for select lat,lng from googlemaps, but does not for the address column
My code is:
<?php
$con=mysqli_connect("localhost","root","","googlemaps");
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql = "SELECT lat,lng,`addr` FROM infos";
if ($result = mysqli_query($con, $sql))
{
$resultArray = array();
$tempArray = array();
// Loop through each row in the result set
while($row =mysqli_fetch_array($result))
{
// Add each row into our results array
$tempArray = $row;
array_push($resultArray, $tempArray);
}
$fp = fopen('results01.json', 'w');
fwrite($fp, "{ \"tab\": ");
fwrite($fp, json_encode($resultArray));
fwrite($fp, " }");
fclose($fp);
echo json_encode($resultArray);
//var_dump($resultArray);
?>
Screenshot of infos table:

Just found the solution it s actually adding this before the select query :
mysqli_set_charset($con, "utf8");
$sql = "SELECT lat,lng,`addr` FROM infos";
if ($result = mysqli_query($con, $sql))
{......}

Related

MySQL Query Returns 0 When Running Multirowed Response Query

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

Retrieve Value of a single column

I need to retrieve data from a single column and put in an API (Json), but for some reason I get the title from the column as well.
$sql = "SELECT workingJson FROM dataTable";
I assumed it would be like workingJson.Value, but no luck.
Here is the API.php
// Create connection
$con=mysqli_connect("localhost","user","password","database");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
// This SQL statement selects ALL from the table 'Locations'
$sql = "SELECT column1 FROM database";
// Check if there are results
if ($result = mysqli_query($con, $sql))
{
// If so, then create a results array and a temporary one
// to hold the data
$resultArray = array();
$tempArray = array();
// Loop through each row in the result set
while($row = $result->fetch_object())
{
// Add each row into our results array
$tempArray = $row;
array_push($resultArray, $tempArray);
}
// Finally, encode the array to JSON and output the results
echo json_encode($resultArray);
}
// Close connections
mysqli_close($con);
Edit per your comments:
To just return the values and not the keys in PHP, you could change your code to this:
// Loop through each row in the result set
while($row = $result->fetch_object())
{
// Add value to array
array_push($resultArray, $row->column1);
}
You have no need for $tempArray in this case.
you can get all results and after doing a traitment :
<?php
// Create connection
$con=mysqli_connect("localhost","user","password","database");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
// This SQL statement selects ALL from the table 'Locations'
$sql = "SELECT column1 FROM database";
if ($result = $mysqli->query($sql)) {
//get all fields :
$finfo = $result->fetch_fields();
foreach ($finfo as $val) {
$resultArray[] = $val->column1;
}
$result->close();
}
// Finally, output the results without encode because is also in json format:
echo '{'. implode(','.chr(10), $resultArray) .'}';
$mysqli->close();

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.

How to generate JSON in realtime/dynamically from a MySQL database

So I want to export a JSON file from a MySQL database table, a php script that runs weekly and exports JSON file from a specific table.
This is sort of the thing I want to achieve:
<?php
$json_file_name = "File_export.json";
$json_file_name = str_replace(" ", "_", $json_file_name);
$con = mysqli_connect("", "", "", "");
if (mysqli_connect_errno($con)) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$date_range = array(
"start" => date("Y-m-d H:i:s", strtotime("-7 days")),
"end" => date("Y-m-d H:i:s", strtotime("now")),
);
and so on
if(!empty($json_data) && count($json_data) > 1)
{
$json_file_data = "";
$fp = fopen($json_file_name, 'w');
foreach($json_data as $row)
{
$json_file_data .= implode(",", $row) . "\n";
}
fwrite($fp, $json_file_data);
fclose($fp);
What is the best way to achieve the same.
Thank you :)
If your database table not too large, you can fetch all rows into a single array, then turn that array into JSON automatically without looping. This will generate JSON with column values as a list:
// $con is connection, $json_filename is name of filename to write
$query = "select * from MyTable";
// Fetch all rows into $json_data array
$result = mysqli_query($con, $query);
$json_data = mysqli_fetch_all($result);
mysqli_close($con);
// Turn data into JSON and write to file
$json = json_encode($json_data);
file_put_contents($json_filename, $json);
Example output:
[["name1","address1"],["name2","address2"]]
If your database table is a little bigger, it is better to write each line as it is generated. The code below will create a JSON object for each row.
$query = "select * from MyTable";
$result = mysqli_query($con, $query);
// Open output file
$fp = fopen($json_file_name, 'w');
// Write JSON list start
fwrite($fp, '[');
// Write each object as a row
$isFirstRow = true;
while ($row = mysqli_fetch_assoc($result)) {
if (!$isFirstRow) {
fwrite($fp, ',');
} else {
$isFirstRow = false;
}
fwrite($fp, json_encode($row));
}
// Write JSON list end
fwrite($fp, ']');
// Close file and MySQL connection
fclose($fp);
mysqli_close($con);
Example output:
[{"name": "name1", "address": "address1"},{"name": "name2", "address": "address2"}]
I think you also want to change this line:
$json_file_data .= implode(",", $row) . "\n";
to this:
$json_file_data[] = implode(",", $row);
Which will cause this:
$json = json_encode($json_data);
To deliver a json array of your database rows.

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