How to retrieve data from mongodb table in php? - php

This is my code in php
public function showData(){
$m = new MongoClient();
$db = $m->newdb;
$collection = $db->createCollection("signup");
$data = $collection->find();
echo "<pre>";print_r($data);exit;
}
but it is returning an empty array while i can see the data in the shell. As we can get the data from mongo shell by writing the command db.signup.find().forEach(printjson);

Every time the function runs, it's trying to create a collection that already exists (unless you delete it before and this part of your code is a re-creating logic - but then it would really be empty at this point).
You can access it with selectCollection():
$collection = $db->selectCollection("signup");

Related

PHP: Should I pass in and return these variables?

I'm currently working on converting my WIP PHP application to an object oriented architecture, as I've found that for my current project good OOP practices are likely to make it much easier. While refactoring my code a bit I came upon a question that is somewhat elementary, but alas I'm not sure of the answer.
I have a section (aka the 'snippet') of code--the code contained in the "GenerateDBSetObjects()" function of the first code sample--that I feel should be put into a function (ie. somewhat like a subroutine), as outlined in the first sample. I want to put it into a separate function block for two reasons:
Simplify the main code body
Create a function that can be unit tested
However, this creates a problem. Because my program effectively has two large scope variables, so I would need to return two values at once (which is no big deal, as it is a common topic: see this). The question that I have though is: Since I am restructuring my code in an Object-Oriented fashion, might there be a more efficient way to do this? Something maybe that I haven't considered? Or is it just best to simply pass in and return the variables?
Because $NumDBSets and $DBSets[] are basically global scope not really sure what I should do here.
index.php
After
//-------------------------Primary Vars---------------------------------------//
//Fills $ini with a multi-dimensional, associative array that contains all of the
// parameters listed in DBSearchConfig.ini
$ini = (parse_ini_file("config/DBSearchConfig.ini", true))
or die ("Config file: 'DBSearchCongif.ini' could not be read or found in the config folder. Please contact the system administrator");
$LogFile = $ini['SystemVars']['LogFile']; //Assign $LogFile to the location of the system's specific log file found in the .ini
$NumDBSets = 0;//An integer which stores the number of Database sets used by the program.
$DBSets = array(); //Creates an empty array that will store each of the DatabaseSet Objects. Each of the
//Database Sets holds an array of SQL database connection parameters (ie.
//Hostname, Username, etc.), as well as an array of links to the SQL databases within the dataset, et. al.
//For more info see 'DatabaseSet.php'
$CurrDBSetNum = $ini['SystemVars']['DefaultDBSet']; //Get the current DBSet Number from config.
$CurrentConnectionManager = new ConnectionManager;
GenerateDBSetObjects($DBSets, $NumDBSets);
//-------------------------FUNCTIONS----------------------------------------//
function GenerateDBSetObjects(){
//Create, Fill and Assign DatabaseSet Objects. Figure out the number of Database sets.
array_push($DBSets, new DatabaseSet);//Push an empty DatabaseSet object into the list to occupy the '0' index!!!
foreach($ini['Databases'] as $ConnectInfoList){
$NumDBSets ++;
//Create a new DatabaseSet Object for this DB Set!!
$newDBSetObject = new DatabaseSet;
$newDBSetObject->ConnectionInfoList = $ConnectInfoList;
$newDBSetObject->CalculateDBSetFields();
array_push($DBSets, $newDBSetObject);
}
}
VS.
Before
//-------------------------Primary Vars---------------------------------------//
//Fills $ini with a multi-dimensional, associative array that contains all of the
// parameters listed in DBSearchConfig.ini
$ini = (parse_ini_file("config/DBSearchConfig.ini", true))
or die ("Config file: 'DBSearchCongif.ini' could not be read or found in the config folder. Please contact the system administrator");
$LogFile = $ini['SystemVars']['LogFile']; //Assign $LogFile to the location of the system's specific log file found in the .ini
$NumDBSets = 0;//An integer which stores the number of Database sets used by the program.
$DBSets = array(); //Creates an empty array that will store each of the DatabaseSet Objects. Each of the
//Database Sets holds an array of SQL database connection parameters (ie.
//Hostname, Username, etc.), as well as an array of links to the SQL databases within the dataset, et. al.
//For more info see 'DatabaseSet.php'
$CurrDBSetNum = $ini['SystemVars']['DefaultDBSet']; //Get the current DBSet Number from config.
$CurrentConnectionManager = new ConnectionManager;
//Create, Fill and Assign DatabaseSet Objects. Figure out the number of Database sets.
array_push($DBSets, new DatabaseSet);//Push an empty DatabaseSet object into the list to occupy the '0' index!!!
foreach($ini['Databases'] as $ConnectInfoList){
$NumDBSets ++;
//Create a new DatabaseSet Object for this DB Set!!
$newDBSetObject = new DatabaseSet;
$newDBSetObject->ConnectionInfoList = $ConnectInfoList;
$newDBSetObject->CalculateDBSetFields();
array_push($DBSets, $newDBSetObject);
}
If you have decided to take an approach with OOP - consider creating a class which will be responsible for generation and storing DatabaseSet objects.
If object of ConnectionManager class is required for DatabaseSets generation, mark it as dependency injection.
Class DatabaseSet should be declared in separate file: DatabaseSet.php.
Let's call our crucial class DatabaseSetAdapter:
require_once("DatabaseSet.php");
class DatabaseSetAdapter
{
private $config;
private $logFile;
private $NumDBSets = 0;
private $DBSets = [];
private $connManager;
private $currDBSetNum;
public function __construct($iniFilePath, ConnectionManager $manager)
{
$this->config = (parse_ini_file($iniFilePath, true))
or die ("Config file: 'DBSearchCongif.ini' could not be read or found in the config folder. Please contact the system administrator");
$this->logFile = $this->config['SystemVars']['LogFile'];
$this->connManager = $manager;
$this->currDBSetNum = $this->config['SystemVars']['DefaultDBSet'];
}
public function generateDBSetObjects()
{
//Create, Fill and Assign DatabaseSet Objects. Figure out the number of Database sets.
$this->DBSets[] = new DatabaseSet; //Push an empty DatabaseSet object into the list to occupy the '0' index!!!
foreach($this->config['Databases'] as $connectInfoList){
//Create a new DatabaseSet Object for this DB Set!!
$newDBSetObject = new DatabaseSet;
$newDBSetObject->ConnectionInfoList = $connectInfoList;
$newDBSetObject->CalculateDBSetFields();
$this->DBSets[] = $newDBSetObject;
$this->NumDBSets++;
}
}
public function getNumDBSets() // a privileged method
{
return $this->NumDBSets;
}
}
// using of DatabaseSetAdapter:
$dbsetAdapter = new DatabaseSetAdapter("config/DBSearchConfig.ini", new ConnectionManager);
$dbsetAdapter->generateDBSetObjects();
$numDbSets = $dbsetAdapter->getNumDBSets();
....
Global scope and OOP don't fit toghether.
You should have an object keeping this info
class DBSets {
private $num;
private $data;
function __construct() {
$this->num = 0;
$this->data = [];
}
//setters and getters for accessing private properties
}
If $num only stores the count of elements in $data, then you can remove it and use
count($this->data);

How to get the size of a list of documents in Mongodb

I am working PHP MongoDB. I am looking for a way to search for a list of documents and find the bsonsize of them in one value. The code below only calculates a single document size. Even if I use Object.bsonsize(db.{$collectionName}.find(), it only gets the cursor right? Is there any way to calculate this without iterating the cursor?
Iterating the cursor to do this is too slow.
Thanks
function documentSizeChecker($collectionName,Array $Criteria){
$connection = db_connect();
$jsonCriteria = json_encode($Criteria);
$code = "function(){
return Object.bsonsize(db.{$collectionName}.findOne({$jsonCriteria}))
}";
$resp = $connection->execute($code);
return $resp["retval"];
}

How to export data from mongodb without displaying headers?

I'm trying to display stored data form the mongodb using the php? But it display's all the header file including data. How to ignore the header information?
It shows like
{ "_id" : ObjectId("550ee694c5c9f2729b066c23"),
I want result as
550ee694c5c9f2729b066c23
my php code:
$db = new Mongo();
$query = $db->selectDB('test');
$collections = new MongoCollection($query,'demo');
$coursor = $collections->find();
foreach ($coursor as $doc)
{print_r($doc);}
You can find the value of the ObjectId() object as a lowercase hexadecimal string using valueOf() method.
ObjectId("550ee694c5c9f2729b066c23").valueOf() = 550ee694c5c9f2729b066c23
For more details you can check documentation :
http://docs.mongodb.org/manual/reference/method/ObjectId.valueOf/
Actually { print_r($doc); } shows header too. There should be some kind of a Key to know which data we need. So we cannot remove them.
$db = new Mongo();
$query = $db->selectDB('test');
$collections = new MongoCollection($query,'demo');
$coursor = $collections->find();
foreach ($coursor as $doc)
{
echo $doc['id'];
}
Will give you only 550ee694c5c9f2729b066c23

Use PHP to load XML Data into Oracle

I'm fairly new to php although I've been programming for a couple years.
I'm working on a project and the end goal is to load certain elements of an xml file into an oracle table on a nightly basis. I have a script which runs nightly and saves a the file on my local machine. I've searched endlessly for answers but have been unsuccessful.
Here is an aggregated example of the xml file.
<?xml version="1.0" encoding="UTF-8" ?>
<Report account="7869" start_time="2012-02-23T00:00:00+00:00" end_time="2012-02-23T15:27:59+00:00" user="twilson" more_sessions="false">
<Session id="ID742247692" realTimeID="4306650378">
<Visitor id="5390643113837">
<ip>128.XXX.XX.XX</ip>
<agent>MSIE 8.0</agent>
</Visitor>
</Session>
<Session id="ID742247695" realTimeID="4306650379">
<Visitor id="7110455516320">
<ip>173.XX.XX.XXX</ip>
<agent>Chrome 17.0.963.56</agent>
</Visitor>
</Session>
</Report>
One thing to note is that the xml file will contain several objects which I will need to load into my table and the above example would just be for two rows of data. I'm familiar with the whole process of connecting and loading data into oracle and have setup similar scripts which perform ETL of txt. and csv. files using php. Unfortunately for me in this case the data is stored in xml. The approach I've taken when loading a csv. file is to load the data into an array and proceed from there.
I'm pretty certain that I can use something similar and perhaps create variable for each or something similar but am not really too sure how to do that with an xml. file.
$xml = simplexml_load_file('C:/Dev/report.xml');
echo $xml->Report->Session->Visitor->agent;
In the above code i'm trying to just return the agent associated with each visitor. This returns an error 'Trying to get property of non-object in C:\PHP\chatTest.php on line 11'
The end result would be for me to load the data into a table similar to the example I provided would be to load two rows into my table which would look similar to below however I think I can handle that if i'm able to get the data into an array or something similar.
IP|AGENT
128.XXX.XX.XX MSIE 8.0
173.XX.XX.XXX Chrome 17.0.963.56
Any help would be greatly appreciated.
Revised Code:
$doc = new DOMDocument();
$doc->load( 'C:/Dev/report.xml' );
$sessions = $doc->getElementsByTagName( "Session" );
foreach( $sessions as $session )
{
$visitors = $session->getElementsByTagName( "Visitor" );
foreach( $visitors as $visitor )
$sessionid = $session->getAttribute( 'realTimeID' );
{
$ips = $visitor->getElementsByTagName( "ip" );
$ip = $ips->item(0)->nodeValue;
$agents = $visitor->getElementsByTagName( "agent" );
$agent = $ips->item(0)->nodeValue;
echo "$sessionid- $ip- $agent\n";
}}
?>
The -> operator in PHP means that you are trying to invoke a field or method on an object. Since Report is not a method within $xml, you are receiving the error that you are trying to invoke a property on a non-object.
You can try something like this (don't know if it works, didn't test it and haven't written PHP for a long time, but you can google it):
$doc = new DOMDocument();
$doc->loadXML($content);
foreach ($doc->getElementsByTagName('Session') as $node)
{
$agent = $node->getElementsByTagName('Visitor')->item(0)->getElementsByTagName('agent')->item(0)->nodeValue;
}
edit:
Adding stuff to an array in PHP is easy as this:
$arr = array();
$arr[] = "some data";
$arr[] = "some more data";
The PHP arrays should be seen as a list, since they can be resized on the fly.
I was able to figure this out using simplexml_load_file rather than the DOM approach. Although DOM works after modifying the Leon's suggestion the approach below is what I would suggest.
$xml_object = simplexml_load_file('C:/Dev/report.xml');
foreach($xml_object->Session as $session) {
foreach($session->Visitor as $visitor) {
$ip = $visitor->ip;
$agent = $visitor->agent;
}
echo $ip.','.$agent."\n";
}

How to get results from "Elastica_ResultSet" object

I am using the "elastica" php client for ElasticSearch.
I'm a bit new to OO-programming, especially in php.
However, I have managed to search my elasticsearch server using the elastica php client and store the response in an "Elastica_ResultSet" object. I have had no luck accessing the contents of that object whatsoever.
I would like to be able to list the total number of results, find an elasticsearch record id of a result and get the full content of an elasticsearch record for that result.
The Elastica class reference can be found here http://ruflin.github.com/Elastica/api/index.html , although I don't know what to do with it.
Here is the php code I have been using to get this far:
<?php
function __autoload_elastica ($class) {
$path = str_replace('_', '/', $class);
if (file_exists('extentions/' . $path . '.php')) {
require_once('extentions/' . $path . '.php');
//echo "$path EXISTS!!!";
}
}
spl_autoload_register('__autoload_elastica');
// New ES Client
$client = new Elastica_Client();
// Set Index
$index = $client->getIndex('test1');
// Set Document Type
$type = $index->getType('user');
// Perform Search
$resultSet = $index->search('halo');
?>
So basicaly you can use var_export to output your resultset
But in general the elastica search returns a Elastica_ResultSet object which has several attributes you can use like count, totalHits facets and so on.
and also holds an array of Elastica_Result objects these can be accessed either by calling the Elastica_ResultSet getResults() method or by using the current() and next() methods or by simply using the php foreach function
The Elastica_Result the data of the results and also has several methods you can use.
getId(), getVersion(), getData() and so on.
// Set Document Type
$type = $index->getType('user');
// Perform Search
$resultSet = $index->search('halo');
// Get IDs
$resultIDs = array();
foreach($resultSet as $result){
$resultIDs[] = $result->getId();
}
I would like to let you know something that was a bit hard for me to get.
The query and the sorting of results
// Set the query terms for your search
$queryTerm = new Elastica_Query_Terms();
$queryTerm->setTerms('user', array("test", "test1"));
// Create the sorting array
$sort = array("user" => array("order" => "desc"));
// Create the query
$query = Elastica_Query::create($queryTerm);
// Set the sorting to the query
$query->setSort($sort);
// Perform the search
$resultSet = $index->search($query);
Hope this helps
After a couple of months OO practise, it seemed performing a simple var_dump($resultSet) would have provided me with the structure and contents of the returned object... can't believe that nobody made any suggestions for such a basic question ;)

Categories