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.
Related
I have some PHP code that successfully exports a MySQL table to a CSV file.
I would like to add to that code, so instead of saving locally the CSL file is exported to/saved on an external FTP server.
My current code:
//open database connection
require ('../database-config.php');
//name the file
header('Content-Type: text/csv');
header('Content-Disposition: attachment;filename=exported-data.csv');
//SQL Query for Data
$sql = "SELECT * FROM data;";
//Prepare Query, Bind Parameters, Excute Query
$STH = $dbh->prepare($sql);
$STH->execute();
//Export to .CSV
$fp = fopen('php://output', 'w');
$first_row = $STH->fetch(PDO::FETCH_ASSOC);
$headers = array_keys($first_row);
fputcsv($fp, $headers); // put the headers
fputcsv($fp, array_values($first_row)); // put the first row
while ($row = $STH->fetch(PDO::FETCH_NUM)) {
fputcsv($fp,$row); // push the rest
}
fclose($fp);
I know I'll need to add some new variables;
$ftp_server="ftp.remotersite.com";
$ftp_path="/path/to/somefile";
$ftp_username="username";
$ftp_userpass="password";
But, I'm not sure the best way to use ftp_put (or should it be ftp_fput?) to transfer to the external destination.
Thanks in advance.
If you have ftp:// URL wrappers enabled, just open the file directly on FTP server:
$fp = fopen('ftp://username:password#ftp.example.com/path/to/somefile', 'w');
If you do not have the wrapers enabled, see:
Creating and uploading a file in PHP to an FTP server without saving locally
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);
I am working on a project and new to PHP and I need to know how to export the table data from SQLite to Excel.
I am able to do it from database but I do not know how to export to Excel using PHP.
<?php
$db = new sqlite3('I:\Preeti\explor\WebMobility.db');
$results = $db->query('SELECT * FROM VerbaliData');
while ($row = $results->fetchArray()) {
var_dump($row);
}
?>
The easiest method whould be to write your results into a CSV file which opens in Excel in a readable format.
See here for more information: http://php.net/fputcsv
$fp = fopen('file.csv', 'w');
while ($row = $results->fetchArray()) {
fputcsv($fp, $row);
}
fclose($fp);
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
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.