Php JSON encoding gives result {"table":null} - php

I didn't work with json before. Im trying to generate a .json file from the data of my sql database.
$con=mysqli_connect(...);
$response = array();
$partik = array();
$result = mysqli_query($con,"SELECT * FROM partik");
while($row=mysqli_fetch_array($result))
{
$nev=$row['im'];
$leiras=$row['leiras'];
$kezdes=$row['kezdes'];
$hely=$row['hely'];
$partik[] = array('im'=> $nev, 'leiras'=> $leiras, 'kezdes'=> $kezdes, 'hely'=> $hely);
}
$response['partik'] = $partik;
$fp = fopen('results.json', 'w');
fwrite($fp, json_encode($response));
fclose($fp);
The sql connection works.
What is wrong in my code? I get a .json file, but with null value.

try this in your while
$row = mysql_fetch_array($result, MYSQL_ASSOC)
like that you will get an associatif array

Related

generate pipe delimited file through codeigniter

I am using the below for csv export but i want to export as a pipe delimeted output text file format.
My code generates a txt file using PHP's fputcsv function.
For the delimiter, I am trying to use '|'.
this mycode:
function to_CSV($table) {
$file_csv = "file_csv.csv";
$fp = fopen('php://output', 'w');
$query = "SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA='htmltable' AND TABLE_NAME='$table'";
$result = mysqli_query(db_connect(),$query);
while ($row = mysqli_fetch_row($result)) {
$header[] = $row[0];
}
header('Content-type: application/csv');
header('Content-Disposition: attachment; filename='.$file_csv);
fputcsv($fp, $header);
$query ="SELECT * from $table";
$result = mysqli_query(db_connect(),$query);
while($row = mysqli_fetch_row($result)) {
fputcsv($fp, $row);
}
exit;
}
fclose($fp);
$contents = file_get_contents($file_csv);
$contents = str_replace(",", "|", $contents);
file_put_contents($file_csv, $contents);
How to implementation in codeigniter. help me out please.
thanks a lot.
according to the docs fputcsv format line as CSV and write to file pointer, it has a third parameter which expects a delimiter - take a look at
https://www.php.net/manual/en/function.fputcsv
In your case it means
while($row = mysqli_fetch_row($result)) {
fputcsv($fp, $row, '|');
}
however the main question is - if you use Codeigniter as underlying Framework - why dont you use the model principle and aside of that the provided query builder? - it will make your life much easier.
You can find more informations in their very well written documentation. Take a look at https://codeigniter.com/user_guide/general/models.html?highlight=model

Perform CRUD operation on json using angular.?

Generated a .json file using php from my SQL database.
I am using angular in frontend and php as backend.
`
$query = "SELECT * FROM users";
$rows = array();
$result = mysqli_query($connection,$query);
while($r = mysqli_fetch_assoc($result)){
$rows[] = $r;
}
print json_encode($rows);
$fp = fopen('results.json', 'w');
fwrite($fp, json_encode($rows));
fclose($fp);
I need to perform CRUD.How should i do that so my .json file automatically updates.?
You can make a change.php or update.php file which will simply overwrite your .json file on the server side when executed.
<?php
$data = json_decode(file_get_contents("php://input"),true);
file_put_contents('file.json', $data);
?>
Now, you can fetch the file.json from server by $http.get() and store it into your $scope or any other variable in angularjs.
Then you may do your CRUD operations on that variable.
All you need to do now is to call the $http.post('URL/chage.php',YOUR_VARIABLE)
This will simply overwrite your .json file with new content.
So whenever you request to get json from .json file, you will always get the updated content.

Insert Mysql data into Json file doesn't work

I have a script that doesn't work I hope some developers of you know the solution.
<?php
//Create Database connection
$db = mysql_connect("localhost","d","d");
if (!$db) {
die('Could not connect to db: ' . mysql_error());
}
//Select the Database
mysql_select_db("d",$db);
//Replace * in the query with the column names.
$result = mysql_query("select * from events", $db);
//Create an array
$json_response = array();
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
$row_array['id'] = $row['id'];
$row_array['title'] = $row['title'];
$row_array['start'] = $row['start'];
$row_array['end'] = $row['end'];
//push the values in the array
array_push($json_response,$row_array);
}
echo json_encode($json_response);
$file = 'events.json';
// Open the file to get existing content
$current = file_get_contents($file);
// Append a new person to the file
// Write the contents back to the file
file_put_contents($file, $json_response);
//Close the database connection
?>
But the events.json is empty? Does anyone know the solution?
first,
echo json_encode($json_response);
file_put_contents($file, $json_response);
this is not writing json you should do this
file_put_contents($file, json_encode($json_response));
maybe it's the issue, you can't write an array into a file.
second, are you missing some code ?
$current = file_get_contents($file);
// Append a new person to the file
we don't see the code to append here, your code just replaces the content by the array $json_response (and not a json encoded array).
You haven't stored the json encoded response anywhere. Below your echo statement, add the line:
$json_response = json_encode($json_response);
You write: // Append a new person to the file but never append, rather replaces the content of the file.
When you call file_put_contents($file, $json_response); you have not yet made $json_response into a json string.
Try change:
echo json_encode($json_response);
To:
$json_response = json_encode($json_response);
To correctly convert the data to a json-string.
To append the data to the file (now I'm going to assume that the file contains data formatted the same as the data you are trying to write), load it as you do with file_get_contents then convert the content to an associative array with: json_decode($dataFromFile, true); (the true flag as second argument makes the return value into an associative array, rather than an object) and merge the two lists, before writing it to file.
use this :
$json_response = json_encode($json_response);

Making a JSON call from PHP

Not sure why but I am not getting anything back from the json call. I echo'ed the content out and pasted to my url bar of my browser and it works. Is there some sort of domain problem here that I need to address?
$connect = open_db();
$result = mysql_query("SELECT search_id, search_term FROM search WHERE search_poi_id IS NULL");
while($row = mysql_fetch_assoc($result)){
$call = "http://maps.google.com/maps/api/geocode/json?address=".$row["search_term"]."&sensor=false";
$json = file_get_contents($call);
print_r($json);
}
close_db($connect);
file_get_contents() may not always work for external URLs. From php.net:
A URL can be used as a filename with this function if the fopen wrappers have been enabled. See fopen() for more details on how to specify the filename. See the Supported Protocols and Wrappers for links to information about what abilities the various wrappers have, notes on their usage, and information on any predefined variables they may provide.
So the echo-ing works? Thus, there is valid JSON? And now what is the problem? If you want JSON to an Array, then json_decode() is what you want.
See http://php.net/manual/en/function.json-decode.php for more info.
If You want to further process the data, You could do it like this:
$data = array();
$connect = open_db();
$result = mysql_query("SELECT search_id, search_term FROM search WHERE search_poi_id IS NULL");
while($row = mysql_fetch_assoc($result)){
$call = "http://maps.google.com/maps/api/geocode/json?address=".$row["search_term"]."&sensor=false";
$data[] = json_decode(file_get_contents($call));
}
close_db($connect);
foreach($data as $d)
print_r($d);
With this data which should be an array of arrays You can then do whatever You want...
EDIT:
If file_get_contents() is not working, try this:
$data = array();
$connect = open_db();
$result = mysql_query("SELECT search_id, search_term FROM search WHERE search_poi_id IS NULL");
while($row = mysql_fetch_assoc($result)){
$call = "http://maps.google.com/maps/api/geocode/json?address=".$row["search_term"]."&sensor=false";
$handle = fopen($call, "rb");
$contents = stream_get_contents($handle);
fclose($handle);
$data[] = json_decode($contents);
}
close_db($connect);
foreach($data as $d)
print_r($d);

mysql foreach fwrite

I use some code here, transfer mysql query data into json data and write into a file. where is the problem? why the file is zero kb?
while($row = mysql_fetch_array($Query)){
$arr = array ('name'=>$row['name']);
$jsondata = json_encode($arr);
$countfile="data.txt";
if(!file_exists($countfile))
{
fopen($countfile,"w");
}
$fp = fopen($countfile, 'r');
fwrite($fp, $jsondata);
fclose($fp);
}
Several things.
You dont need (and should avoid) to open the file in every iteration
You open the file read-only (r)
At all something like this should do it
$countfile="data.txt";
$fp = fopen($countfile, 'w');
while($row = mysql_fetch_array($Query))
{
$arr = array ('name'=>$row['name']);
$jsondata = json_encode($arr);
fwrite($fp, $jsondata);
}
fclose($fp);
Additional you append separate json structures into the file, what is probably not, what you want. You should first collect all you want to store into one json structure and save it then
$data = array();
while($row = mysql_fetch_array($Query))
{
$data[] = array ('name'=>$row['name']);
}
file_put_contents('data.txt', json_encode($data));
This feels more like what you are probably looking for.
Because you're reopening the file as read only
$fp = fopen($countfile, 'r');
try
$fp = fopen($countfile, 'w'); // to write
or
$fp = fopen($countfile, 'a'); // to append
you could also open the file for writing at the start, append your rows in a variable and then write it all together to the file.
$countfile="data.txt";
$fp = fopen($countfile, 'w');
while($row = mysql_fetch_array($Query))
{
$arr = array ('name'=>$row['name']);
$jsondata .= json_encode($arr) . "\n";
}
fwrite($fp, $jsondata);
fclose($fp);
You are opening the file read-only. You probably want 'w' or 'r+'.
You are opening the file for reading only
$fp = fopen($countfile, 'r');
You also dont need
if(!file_exists($countfile))
{
fopen($countfile,"w");
}
just use:
$fp = fopen($countfile, 'w');

Categories