Insert Mysql data into Json file doesn't work - php

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

Related

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.

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

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

PHP convert JSON object to string

I am making a quiz script. I want a "teacher" to be able to edit the questions. Originally, I tried to use mySQL but it was a bit difficult, so I decided to switch to a JSON file.
After doing some basic checks with PHP, I wrote this block of code
$json = array();
for ($x=1; $x < $count + 1; $x++) {
$q_and_a = array(
"Question" => $_POST["q".$x],
"Answer" => $_POST["a".$x]
);
array_push($json, $q_and_a);
}
$encoded_array = json_encode($json);
// Delete JSON file, create new one and push encoded array into file
$json_file = 'questions.json';
unlink($json_file);
$handle = fopen($json_file, 'w') or die('Cannot open file: '.$json_file);
fwrite($handle, $json_string) or die('Internal Sever Error');
After I got an internal server error, I realized that this is because the $json variable is an array; I need to convert it into a string and then insert it into the file. I first used serialize() but that just inserted some weird stuff into my file. How do I convert the json array into a string before moving it into the file?
Thanks In Advance
Try this piece of code. It doen't use JSON but it still saves data into a file which is split up using tab
<?php
$count=10;//whatever you defined it to
$qa = "";
for ($x=1; $x < $count + 1; $x++) {
$qa .= $_POST["q".$x]."\t".$_POST["a".$x]."\n";
}
$json_file = 'file.txt';
unlink($json_file);
file_put_contents($qa);
?>
<?php
//to retrieve q&a
$qas = file('file.txt',FILE_IGNORE_NEW_LINES|FILE_SKIP_EMPTY_LINES);
$qas = explode("\t",$qas);
foreach($qas as $question => $answer)
{
//your code
}
?>
fwrite($handle, $encoded_array) or die('Internal Sever Error');

storing live data in Mongodb

I am pushing data to a server using an API from a website. Every time my arduino detects a pulse it sends it to COSM. And by using a trigger, the data goes to my server. I was initially writing the data into a .txt file and a Json object, but now I want to start implementing mongo to have different collections.
For some reason the data is not being transmitted to my server after I added the Mongo connection when I tried to write it as a Mongo collection. I want to be able to write down the information in Mongo directly and avoid creating files.
Any suggestion is more than welcome, here is the code:
<?php
// Creating a data base in Mongodb to store my information from my $jsonFile
$connection = new MongoClient(); //Connect to mongo
$db = $connection -> qandm; // select my DB which is called qandM
$collection = $db -> pulseData;
//Gets all the information from Cosm
$pulse = $_POST['body'];
//access and open a file
//echo $pulse;
//Converts the data into PHP arrays
$pulseObj = json_decode($pulse, true);
//Parse through the specific information from the array and gets each piece of information in an array
$userName = $pulseObj["triggering_datastream"]["id"];
$dataTime= $pulseObj["triggering_datastream"]["at"];
$dataValue= $pulseObj["triggering_datastream"]["value"]["value"];
//Writes all the data coming from COSM
$file = fopen("data.txt", "a+");//a+ give the option to have the cursor at the end to access the file read and write it
/* $pulse.="\r\n"; */
fwrite($file, $pulse);//takes incoming data and writes it in the file
fclose($file);
//Opens a new .txt file and writes the values that we selected before into our file
$string = $userName." ".$dataTime." ".$dataValue." \r\n";
//error_log allows me to see in my Apache log server the information that I'm printing
error_log($string);
//Write all the information I parsed in my three variables in a new file
$file2 = fopen("rawData.txt", "a+");
fwrite($file2,$string);
fclose($file2);
//json sample
//Inputs the data from the time and the pulse value into a json object
$json = array("User" => $userName, "timestamp"=> $dataTime, "value"=> $dataValue);
//Opens a new json object
$jsonFile = fopen("data.json", "a+");
//Writes the data of our new arrayed information into the open json object
fwrite($jsonFile, json_encode($json));
fclose($jsonFile);
//A loop to populate
foreach($json as $data){
$collection->insert($data);
}
//find the data I just stored
$cursor = $collection->find();
//Output it in a UL
echo "<p> My Pulse </p>";
echo '<ul>';
foreach($cursor as $doc){
echo' <li> My pulse is: '.$doc['value'];
}
echo '</ul>';
/*$data = "data.txt";
$fh = fopen($data, "w") or die ("can't open file");
$data = json_encode($_POST);
fwrite($fh, $data);
fclose($fh);*/
//print_r($file);
?>
This is likely the source of your problems:
//A loop to populate
foreach($json as $data){
$collection->insert($data);
}
You are iterating over your $json array and passing the values (but not the keys) to the insert method of MongoCollection. According to the doc this method expects an object or an array. Based on what I understand your code to be trying to do this foreach loop should be replaced with the following:
$collection->insert($json);
This will create a mongo object resembling your array. Your code currently is attempting to insert the values of each array element as an individual entry.

file_get_contents into a json variable- twitter module

I am extremely new to json and have been working on this issue for about a week.
I used php to retrieve tweets from a list of accounts and stored them into a .txt file
$cache = dirname(__FILE__) . '/../cache/twitter-json.txt';
$data = file_get_contents('http://api.twitter.com/1/lists/statuses.json? slug=widget&owner_screen_name=webcodepro&count=1&page=1&per_page=8&include_rts=true&include_entities=true');
$cachefile = fopen($cache, 'wb');
fwrite($cachefile,utf8_encode($data));
fclose($cachefile);
?>
The way the architect has the front-end page structured is that I need to store the json value (what I have in the .txt file) into a json variable in a .js file and render it.
edit:
so it has been changed to
$cache =_ _DIR__.'/cached.txt';
$data = file_get_contents('http://api.twitter.com/1/lists/statuses.json? slug=widget&owner_screen_name=webcodepro&count=1&page=1&per_page=8&include_rts=true&include_entities=true');
file_put_contents($cache, $data);
the file comes up empty. do you guys know what might be the problem?
Is it possible to store the contents of a .txt file into a json variable in a .js file?
No need to utf8_encode things as JSON is already UTF-8
You can simply use file_put_contents
file_put_contents($cache, 'var myvar = '.$data.';');
-edit-
Code to clarify my solution:
$cache = __DIR__.'/cached.txt';
$data = file_get_contents('http://api.twitter.com/1/lists/statuses.json?slug=widget&owner_screen_name=webcodepro&count=1&page=1&per_page=8&include_rts=true&include_entities=true');
file_put_contents($cache, 'var mydata = '.$data.';');
Is it possible to store the contents of a .txt file into a json variable in a .js file?
Yes, it is possible:
$txtFile = '/path/to/txt-file.txt';
$jsFile = '/path/to/js-file.js';
$jsPlate = "var jsVariable = %s;\n";
$string = file_get_contents($txtFile);
if (FALSE === $string) {
throw new RuntimeException('Failed to load text-file.');
}
$json = json_encode($string);
if (FALSE === $json) {
throw new RuntimeException('Failed to json encode string.');
}
$jsString = sprintf($jsPlate, $json);
$result = file_put_contents($jsFile, $jsString);
if (!$result) {
throw new RuntimeException('Failed to save javascript-file.');
}
Encoding Checklist:
The text-file is UTF-8 encoded.

Categories