storing live data in Mongodb - php

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.

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.

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

Php MongoDB Write a CSV File

I have searched the internet, and could not get any specific details about it.
The environment is Windows 8, WAMP , MONGODB
I am trying to design a webpage, which have 4 fields: Name,Contact,Device,Email. After an user hits the submit button, the data inserts in the MongoDb. All this works fine.
The issue starts when I try to write the inserted data in the csv file, as this is the requirement. I have tried MongoDB Export command in the cmd, and it works fine, but trying to call the same using exec function in the php script is proving to be futile.
I have tried with this also, by storing the command in a .bat file, and then calling the .bat file using the php's exec function, still, no effect
<?php
echo '<pre>';
// Outputs all the result of shellcommand "ls", and returns
// the last output line into $last_line. Stores the return value
// of the shell command in $retval.
exec("c:\WINDOWS\system32\cmd.exe /c START C:\wamp\bin\mongodb\mongodb-win32-x86_64-2008plus-2.4.3\conf\export.bat");
?>
I have enabled the checbox interaction with desktop in my WAMP server.
I don't need any specific help related with the coding, all I need is some direction on how to proceed ahead, as I know that I am missing something. Also, I reiterate, did not get anything specific on the Internet, hence, posting the question.
Kindly let me know on how to achieve this.
Thanks to everyone
The following may work
header('Content-Type: application/csv');
header('Content-Disposition: attachment; filename=example.csv');
header('Pragma: no-cache');
$database = "DATABASE";
$colName = "COLLECTION";
$connection = new MongoClient();
$collection = $connection->$colName->$database;
$cursor = $collection->find();
foreach($cursor as $cur)
echo '"'.$cur['field_1'].'","'.$cur['field_2']."\"\n";
This code will dump your selected database to the a json file
$mongoExport = 'c:\mongodb\mongoexport'; //full path to mongoexport binary
$database = 'test';
$collection = 'foo';
$file = "c:\\temp\\foo.json"
exec(sprintf("%s -d %s -c %s -o %s",
$mongoExport,
$database,
$collection,
$file
));
And this is using pure PHP, for sure will be more fast the mongoexport option, with large collections:
$database = 'test';
$collection = 'foo';
$m = new MongoClient();
$col = $m->selectDB($database)->$collection;
$json = json_encode(iterator_to_array($col->find()));
set_time_limit(0);
ob_start();
error_reporting(E_ALL);
ini_set("display_errors",1);
$conn = new MongoClient("mongodb://Hostname:27017", array("replicaSet" => "rs0"));
if(!$conn){
die("Unable to connect with mongodb");
}
$db = $conn-><DB NAME>; // DB name
$col1 = $db-><colname>;
$col2 = $db-><colname>; // collection name which u want .
$filterCountry = array("status"=>"1"); // where query
$records = $col1->find($filterCountry);
$fp= fopen('exampleTest11.csv', 'w'); // open csv file in which u want write data.
$headings[] = "Code";
$headings[] = "Status" ;
$headings[] = "EMP CODE";
fputcsv($fp, $headings); // PUT Headings .
$cnt =0;
foreach($records as $val) {
$csvarr = array();
$csvarr['code']= $val['code']; // fetch data from database.
$csvarr['Status']= $val['status'];
$csvarr['emp_code']= $val['emp_code'];
fputcsv($fp, $csvarr);
$cnt++;
}
echo "Completed Successfully..".$cnt;

Uploading and downloading a 2 dimensional array using file_put_contents file_get_contents - php

Hopefully, I won't be a novice for long. I have a 2-dimensional array (simplified) that I'm trying to work with. Simply pulling out, adding to, and uploading a file record. Can somebody forgive my ignorance and explain what I'm doing wrong?:
<?php
// Updating Current Number of Vendors
$vendorcount = #file_get_contents('../Keys/VendorCount/$v');
if(isset($vendorcount))
{
$new_vendor_number = ($vendorcount + 1);
$n = $new_vendor_number;
}
else
{
$vendorcount = 0;
$new_vendor_number = 1;
$file = '../Keys/VendorCount/$v' ;
file_put_contents($file, $vendorcount) ;
};
//getting record from file
$record = file_get_contents('../Vendors/$vendorlist');
//adding new information to record array
$record[$n] = array($new_vendor_number, $catname);
//uploading updated record
$file = '../Vendors/$vendorlist' ;
file_put_contents($file, $record) ;
?>
You need to use serialize() and unserialize() in order to store an array to a file or restore it from a file. Like this:
$array = array(1,2,3);
// writing to file
file_put_contents('file.txt', serialize($array));
// restoring from file
$array = unserialize(file_get_contents('file.txt'));
This will work with arrays of any dimension.

Persistent Date Stamp - write/read to file

I'm trying to set a persistent date stamp by writing it to a text file and then reading it back in each time the page is viewed.
// set the date, w/in if statements, but left out for brevity
$cldate = date("m/d/Y");
$data = ('clickdate' => '$cldate'); // trying to set a variable/value pair
- It's throwing an Error on this !
// Open an existing text file that only has the word "locked" in it.
$fd = fopen("path_to_file/linktrackerlock.txt", 'a') or die("Can't open lock file");
// Write (append) the pair to the text file
fwrite($fd, $data);
// further down …
// Open the text file again to read from it
$rawdata = fopen("path_to_file/linktrackerlock.txt", 'r');
// Read everything in from the file
$cldata = fread($rawdata, filesize("path_to_file/linktrackerlock.txt"));
fclose($rawdata);
// Echo out just the value of the data pair
echo "<div id='Since'>Clicks Since: " . $cldata['clickdate'] . "</div>";
$data = ('clickdate' => '$cldate');
needs to be:
$data = array('clickdate' => $cldate);
Additionally, you are required to pass a string to an fwrite statement, so there is no need to create an array:
$cldate = date("m/d/Y");
if($fd = fopen("path_to_file/linktrackerlock.txt", 'a')){
fwrite($fd, $cldate);
fclose($fd);
}else{
die("Can't open lock file");
}
Code's fundamentally broken. You're trying to create an array, then write that array out to a file:
$data = array('clickdate' => '$cldate');
^^^^^---missing
Then you have
fwrite($fd, $data);
But all that will do is write the word Array out to your file, NOT the contents of the array. You can try it yourself... just do echo $data and see what you get.
You could probably make this whole thing a lot simpler with:
$now = date("m/d/Y");
file_put_contents('yourfile.txt', $now);
$read_back = file_get_contents('yourfile.txt');
If you do insist on using an array, then you have to serialize or, or use another encoding format, like JSON:
$now = date("m/d/Y");
$arr = array('clickdate' => $now);
$encoded = serialize($arr);
file_put_contents('yourfile.txt', $encoded);
$readback = file_get_contents('yourfile.txt');
$new_arr = unserialize($readback_encoded);
$new_now = $new_arr['clickdate'];

Categories