Why am I getting a Fatal error with this MongoDB function? - php

I've got a simple php script for getting a csv file into array and inserting each row into MongoDB (CD Collection). But somehow insert returns an error after first successful one:
"Fatal error: in C:\xampp\htdocs\mongo\lesson1\index.php on line 17"
Here's the code. What could possibly cause such an error? DB receives only one (first).
$filename = 'd:/cd_col.csv'; // Each line: Title;No. of CD with movie
$csvfile = fopen($filename,'rb');
while(!feof($csvfile)) {
$csvarray[] = fgetcsv($csvfile);
}
$m = new MongoClient();
$db = $m->mymovies;
$collection = $db->movies;
$id=0;
foreach($csvarray as $key=>$value)
{
$movie = explode(';', $value[0]);
$fmovie = array('_id'=>++$id, 'title'=>$movie[0], 'cdno'=>$movie[1]);
if($collection->save($fmovie)===true) { // this is line 17
echo 'Successful insert: '.$key;
}
}

SOLVED:
Cannot use save in php, that's it.
You should use $collection->insert(); instead.

Related

PHP - PHP Notice: unserialize(): Error at offset in function

I have the following PHP function:
function readDataFile_array($dataFileName) {
if (file_exists($dataFileName)) {
$readFile = fopen($dataFileName, 'r');
$previousData = fread($readFile, filesize($dataFileName));
fclose($readFile);
$previousData = unserialize($previousData);
} else {
$previousData = null;
}
return $previousData;
}
I'm getting the following error: PHP Notice: unserialize(): Error at offset 416687 of 416690 bytes
The data to be read by the function is being saved using the following:
function writeDataFile_array($dataFileName, $insertData) {
$insertData = serialize($insertData);
$writeFile = fopen($dataFileName, 'w') or die('Unable to open file!');
fwrite($writeFile, $insertData);
fclose($writeFile);
}
I'm not sure why I'm getting the error that refers to $previousData = unserialize($previousData);
You are f-reading the wrong chunk size.
The EOF seems to be added to the file size.
Try to get the file by using file_get_contents() which is the proper way to read file data.
$previousData = file_get_contents($dataFileName);

Insert into mongo database does not work - why?

I try to set up some basic fixtures in Mongo DB. To do so I read a set of JSON files and try to insert them into local db (I am connecting with admin rights). Here's the weird part. For some reasons I wrote to versions of the code that should work basically the same so I have one:
$client = new \MongoClient($connectionURI);
$db = $client->selectDB($database);
$collections = $db->listCollections();
foreach ($collections as $collection) {
//echo "Removing all documents from '$collection'" . PHP_EOL;
$collection->remove();
$tmp = explode('.', (string)$collection);
$collectionName = $tmp[1];
$tmp = explode('_', $tmp[0]);
$dbName = $tmp[1];
$country = $tmp[2];
if(file_exists(__DIR__."/fixtures/{$country}/{$dbName}/{$collectionName}.json")) {
echo "Inserting fixture data into '{$collection}'".PHP_EOL;
$data = json_decode(file_get_contents(__DIR__."/fixtures/{$country}/{$dbName}/{$collectionName}.json"));
$doc = $collection->insert($data, ["w" => "majority"]);
}
}
And second one based on iteration of the files to read instead of listing existing collections:
$client = new \MongoClient($connectionURI);
foreach(glob(__DIR__.'/fixtures/*', GLOB_ONLYDIR) as $dir) {
$country = basename($dir);
foreach(glob(__DIR__.'/fixtures/'.$country.'/*', GLOB_ONLYDIR) as $dbDir) {
$collections = array_diff(
scandir(__DIR__."/fixtures/{$country}/".basename($dbDir)), ['.', '..']
);
$dbName = 'test_'.basename($dbDir).'_'.$country;
foreach($collections as $collectionFile) {
$collectionName = pathinfo($collectionFile)['filename'];
$data = [];//json_decode(file_get_contents(__DIR__."/fixtures/{$country}/".basenam e($dbDir)."/{$collectionName}.json"));
// $client->$dbName->$collectionName->insert($data);
$db = $client->selectDB($dbName);
$collection = $db->selectCollection($collectionName);
$collection->insert($data, ["w" => "majority"]);
echo $country.'->'.$dbName.'->'.$collectionName.PHP_EOL;
}
}
}
The trick is that the first implementation works nicely and second throws MongoCursorException with authentication problem. The problem I am having is that both versions try to connect to exact same database and collection in fact. So I am getting following output:
Inserting fixture data into 'test_customers_poland.accounts'
PHP Fatal error: Uncaught exception 'MongoCursorException' with message 'Couldn't get connection: Failed to connect to: 127.0.0.1:27017: SASL Authentication failed on database 'test_customers_poland': Authentication failed.' in /srv/dev-api/src/tests/init_databases.php:96
Stack trace:
#0 /srv/dev-api/src/tests/init_databases.php(96): MongoCollection->insert(Array, Array)
#1 {main}
thrown in /s
rv/dev-api/src/tests/init_databases.php on line 96
Of course I also checked running those snippets separately as well with the same result so the question is: what am I doing wrong in second approach?

How to resolve the com_exception error in php which occurs in reload (reading barcodes from images)?

I am using clear image SDK for reading barcode from images. The code is working only first time on my browser. When I reload the page, it throws an exception. To make it work again, I restart my web server and it works again. But when I reload the page, it again throws the same exception. The error is given below:
( ! ) Fatal error: Uncaught exception 'com_exception' with message '<b>Source:</b> ClearImage.ClearImage.1<br/><b>Description:</b> SEH Exception 0xC0000005' in C:\wamp\www\test.php on line 11
( ! ) com_exception: <b>Source:</b> ClearImage.ClearImage.1<br/><b>Description:</b> SEH Exception 0xC0000005 in C:\wamp\www\test.php on line 11
If I call the script from command line, it works fine and it does not matter if I call the script again. I dont need to restart the webserver at all.
What is exactly going on with this script? Do I need to close any particular resources or connections in the script so that it can work again? This is the first time I am working with COM object.
<?php
try {
// To insert line breaks in HTML output replace \n with <br>
// Create and Configure ClearImage Object
$Ci = new COM("ClearImage.ClearImage");
} catch (Exception $e) {
echo $e->getMessage();
}
// Create the 1D Barcode Pro object. Use any of the other engines here.
$Bc = $Ci->CreateBarcodePro();
// Open file.
$File = 'c39.tif'; // Use YOUR file name
$File = 'C:\\test.jpg';
$Bc->Image->Open($File);
// $Bc->Code39 = true;
// Set reading parameters. Update values if needed. See Online API help
$Bc->AutoDetect1D = 65535;
/*
* my testing
*/
$Bc->Type = 2;
$Bc->Directions = 2;
$Bc->Algorithm = 2;
/*
* my tesing
*/
$Bc->Algorithm = 2;
// Read Barcodes
$BCcount = $Bc->Find(0);
echo "\nBarcodes: $BCcount\n";
if ($BCcount == 0) {
$Msg = "No barcodes found in $File \n";
exit($Msg);
}
for ($i = 1; $i <= $BCcount; $i ++) {
echo "Barcode #$i ";
$FBc = $Bc->BarCodes($i);
// NOTE: Text value will terminate on the first null in data
echo "Type: $FBc->Type Length: $FBc->Length\n";
echo "Barcode Value: $FBc->Text \n";
echo " Binary Data in Hex: \n ";
$hex_ary = array();
$cnt = 0;
foreach ($FBc->Data as $chr) {
$hex_ary[] = sprintf("%02X", $chr);
$cnt = $cnt + 1;
if ($cnt == 16) // break lines after 16 numbers
{
$hex_ary[] = sprintf("\n");
$cnt = 0;
}
}
echo implode(' ', $hex_ary);
echo "\n";
}
unset($Ci);

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;

Error: Non Object on DOMElement

foreach ($filePaths as $filePath) {
/*Open a file, run a function to write a new file
that rewrites the information to meet design specifications */
$fileHandle = fopen($filePath, "r+");
$newHandle = new DOMDocument();
$newHandle->loadHTMLFile( $filePath );
$metaTitle = trim(retrieveTitleText($newHandle));
$pageMeta = array('metaTitle' => $metaTitle, 'pageTitle' => 'Principles of Biology' );
$attributes = retrieveBodyAttributes($filePath);
cleanfile($fileHandle, $filePath);
fclose($fileHandle);
}
function retrieveBodyAttributes($filePath) {
$dom = new DOMDocument;
$dom->loadHTMLFile($filePath);
$p = $dom->getElementsByTagName('body')->item(0);
/*if (!$p->hasAttribute('body')) {
$bodyAttr[] = array('attr'=>" ", 'value'=>" ");
return $bodyAttr;
}*/
if ($p->hasAttributes()) {
foreach ($p->attributes as $attr) {
$name = $attr->nodeName;
$value = $attr->nodeValue;
$bodyAttr[] = array('attr'=>$name, 'value'=>$value);
}
return $bodyAttr;
}
}
$filePaths is an array of strings. When I run the code, it give me a "Call to member function hasAttributes() on non-object" error for the line that calls hasAttributes. When it's not commented out, I get the same error on the line that calls hasAttribute('body'). I tried a var_dump on $p, on the line just after the call to getElementsByTagName, and I got "object (DOMElement) [5]". Well, the number changed because I was running the code on multiple files at once, but I didn't know what the number meant. I can't find what I'm doing wrong.
with:
$p = $dom->getElementsByTagName('body')->item(0);
You are executing: DOMNodelist::item (See: http://www.php.net/manual/en/domnodelist.item.php) which returns NULL if, at the given index, no element is found.
But you're not checking for that possibility, you're just expecting $p to be not null.
Try adding something like:
if ($p instanceof DOMNode) {
// the hasAttributes code
}
Although, if you're sure that there should be a body element, you'll probably have to check your file paths.
It should be because there is no <body> tag in your DOM Document.

Categories