MongoDB PHP connection not working - php

<?php
$m = new MongoClient('mongodb://localhost', array(
'username' => 'wa',
'password' => 'password',
'db' => 'wa'
));
I'm using that code snippet to connect and am trying to run commands in PHP to insert / find data in a MongoDB collection or database.
I installed MongoDB and added the mongo.so extension to my php.ini.
What am I doing wrong?

Can you run just the connection code from the command line. Also you should be passing in your connection options in this format:
mongodb://[username:password#]host1[:port1][,host2[:port2:],...]/db
Use this:
<?php
$m = new MongoClient('mongodb://wa:password#localhost/wa');
?>
That will throw any errors you are having on the command line and be easy to diagnose. The responses should be self explainatory. Likely causes:
You are connecting to localhost and do not have a running mongod or mongos on this machine. [ So change tha host and possibly port].
Your user credentials are incorrect
It seems likely that case 1 applies by the very fact you are supplying user credentials, as you would be unlikely to need them if developing on your own machine. It would also be very uncommon to be running MongoDB on the same server as your application in production.

For anyone that stumbles upon this, the MongoClient is depricated and does not work with the current (as of Aug 2018) MongoDB PHP Driver. (which would be installed with the mongodb.dll file, not the *.so file)
A current example of a working connection would be:
<?php
$user = "XXXX";
$pwd = 'XXXX';
$filter = [];
if (isset($_POST['needleID'])) {
$needleID = $_POST['needleID'];
$filter = ['id'=> $needleID];
}
//Manager Class
$connection = new MongoDB\Driver\Manager("mongodb://${user}:${pwd}#localhost:27017");
// Query Class
$query = new MongoDB\Driver\Query($filter);
// Output of the executeQuery will be object of MongoDB\Driver\Cursor class
$rows = $connection->executeQuery('sedwe.defaultConfig', $query);
// Convert rows to Array and sedn result back to client
$rowsArr = $rows->toArray();
echo json_encode($rowsArr);
?>

Related

Can't connect custom script to cosmos db using brightzone gremlin-php

I'm trying to build an app around the brightzone gremlin php api for cosmos db (free tier). I can get the api to work through the console (with the provided app) but when I try to use my own custom functions to call the exact same methods available in the API class – practically copying the code, which worked through the console) – I get this...
Fatal error: Uncaught TypeError: fwrite(): Argument #1 ($stream) must be of type resource, null given {...}
on line 174 in vendor/brightzone/gremlin-php/src/Connection.php
I'm new to Gremlin in general, and have limited experience using APIs.
Is this some limitation to the free tier, or have I completely misunderstood something?
edit
I decided to test the api with varying degrees of extra setup on my part...
Running the PHP CLI script: connect.php (included in cosmos graph php getting started quickstart) from a browser through xampp gave no errors. I'm seeing a spike in requests in cosmos' dashboard when I do this, so I know it's hitting the database.
The same test through a vhost alias also gave no errors, while hitting the database.
Creating my own function that calls the class and methods results in the fwrite error above.
Initializing the object
This is the same on both the CLI version and my script.
<?php
require_once('define.php');
require_once('vendor/autoload.php');
use \Brightzone\GremlinDriver\Connection;
$db = new Connection([
'host' => HOST,
'username' => USER,
'password' => PASS
,'port' => PORT
// Required parameter
,'ssl' => TRUE
]);
code comparison
Here's the provided CLI script I'm trying to emulate...
function countVertices($db)
{
$query = "g.V().count()";
printf("\t%s\n\tQuery: %s\n", "Counting all the vertices.", $query);
$result = $db->send($query);
if($result)
{
printf("\tNumber of vertices in this graph: %s\n\n", $result[0]);
}
}
This results in an instant readout of the printf commands meant for command line responses, with correct data from the result property of the object, showing it was initialized, and then functioned properly.
but
Here's how I'm trying to call the method...
$query = "g.V().count()";
$result = $db->send($query);
var_dump($result);
The object initializes fine, but calling the send method throws the fwrite error.
Seriously... what am I missing?
I failed to check the END of the CLI php script, which had a "try" catch statement running all the functions. If I had checked, I'd have seen that the open and close methods...
$db->open();
//<--whatever querying here-->
$db->close();
are necessary to get the gremlin driver connected.
It's all working now with:
<?php
require_once('define.php'); //custom script defining credentials as constants
require_once('vendor/autoload.php');
use \Brightzone\GremlinDriver\Connection;
error_reporting(E_ALL ^ E_WARNING);
$db = new Connection([
'host' => HOST,
'username' => USER,
'password' => PASS,
'port' => '443'
// Required parameter
,'ssl' => TRUE
]);
$db->timeout = 0.5;
$db->open();
$query = "g.V().count()";
var_dump($db->send($query));
$db->close();
?>
This prints the correct response.

Insert MongoDB ISODate PHP

I am using the following versions:
PHP -> 5.6.11
MongoDB -> 3.2
MongoDB PHP Driver -> 1.1
When I was looking to install a MongoDB PHP driver here I noticed that the driver named "Mongo" had been deprecated and proceeded to follow the provided link to install the new extension "MongoDB". This will be referred to as php_mongodb. Since I am using a Windows System I had to copy the file php_mongodb.dll to my ../php/ext and added the line extension=php_mongodb.dll to my PHP.ini
Using the now deprecated driver I used to be able to insert a MongoDate() as shown below.
<?php
$connection = new MongoClient();
$database = $connection->selectDB('test');
$coll = new MongoCollection($database, 'users');
$coll->insert(
(object)array(
"createdAt" => new MongoDate()
)
);
?>
The Problem is that with the new php_mongodb this MongoDate() does not seem to be available I receive the error: Fatal error: Class 'MongoDate' not found
What is the equivalent to this using new php_mongodb driver?
Should I consider downgrading my version of MongoDB to 3.0 so that I can use the now legacy Mongo Driver?
Is there a PHP native way to make a date that is of type ISODate?
Should I consider downgrading my version of MongoDB to 3.0 so that I can use the now legacy Mongo Driver?
This is what I've tried to no avail, the following will add a value of type Timestamp to a Document, however it seems that because it is not of type ISODate that I am unable to enforce TTL with this createdAt field:
<?php
require '/vendor/autoload.php';
$date = new MongoDB\BSON\Timestamp(1, date('U'));
$manager = new MongoDB\Driver\Manager("mongodb://127.0.0.1:27017");
$collection = new MongoDB\Collection($manager, "test.users");
$ex = [
"createdAt" => $date
];
$result = $collection->insertOne( $ex );
?>
Another thing I have tried is the below date, however without the MongoDate() functionality I do not know how to insert this as the type ISODate for MongoDB:
date(DATE_ISO8601, date('U'));
not sure if you still need this, but i have been struggling a lot with this. Finally i have been able to figure it out.
$orig_date = new DateTime('2016-01-22 14:00:00');
# or you can use any other way to construct with (int timestamp)
$mongo_date = new MongoDB\BSON\UTCDateTime($orig_date->getTimestamp());
$filter = [
....
....
['timestamp' => ['$gte' => $mongo_date]],
....
....
]
# create command (for example aggregation)
$cmd = new MongoDB\Driver\Command( $filter );
# execute command
$cursor = $manager->executeCommand('my_mongo_db_name', $cmd);
This code works for me.

Using MongoDb in the PHP Phalcon framework

I am currently experimenting with the Phalcon Framework, and running into some complications when I attempt to save content into the Mongo Database. I can correctly setup the MySQL database without issues. Whenever I send the simple request through I get a 500 Internal server error (checking devTools). I have setup everything accordingly as the documentation specifies.
This is my simple index.php bootstrap Mongo initialisation along with the collection manager:
// Setting Mongo Connection
$di->set('mongo', function() {
$mongo = new Mongo();
return $mongo->selectDb("phalcon");
}, true);
// Setting up the collection Manager
$di->set('collectionManager', function(){
return new Phalcon\Mvc\Collection\Manager();
}, true);
This is my controller handling the request:
public function createAction() {
$user = new User();
$user->firstname = "Test ACC";
$user->lastname = "tester";
$user->password = "password";
$user->email = "testing#example.com";
if($user->create() == false) {
echo 'Failed to insert into the database' . "\n";
foreach($user->getMessages as $message) {
echo $message . "\n";
}
} else {
echo 'Happy Days, it worked';
}
}
And finally my simple User class:
class User extends \Phalcon\Mvc\Collection {
public $firstname;
public $lastname;
public $email;
public $password;
public $created_at = date('Y-m-d H:i:s');
}
Much appreciated for everyones input/suggestions.
i think it's because your installation of Mongo is not valid.
try printing phpinfo() and check if mongo is loaded at all, if not - install it, add to ini files (if you use cli, don't forget to add to cli ini too) and reach the moment, when mongo is fully loaded.
try mongo w/o phalcon. any simple connection/insertation. you can see here: Fatal Error - 'Mongo' class not found that there are problems with apache module version for some people. Try reinstalling different mongo version.
if you can print this out:
echo Phalcon\Version::get();
there should be no problems with phalcon instalation
to validate mongo installation, try any of examples from php.net:
http://www.php.net/manual/en/mongo.tutorial.php
A little bit late, but for anyone else facing this issue, it would be a good idea to try and connect to mongo (run "mongo" in your terminal) to ensure that mongo is setup correctly in your dev environment.
Also, I usually find in this sort of situation, that adding a collection to a database in mongo and then testing the CRUD process with a simple read helps move things along. If all is well at this stage, then you know your app is able to connect and you can proceed to writes, and so on.
This looks useful.

mongo authorization zend shanty

I trying to add authorization to mongoDB.
I use mongodb 2.2.4, php-mongo 1.4.1 stable, apache2, php 5.4, ZendFramework 1.12 + ShantyMongo
Also I use replicaset with 3 instances.
When I set auth = true mongo create admin database, and when I add user to this database I got this error:
Fatal error: Uncaught exception 'MongoCursorException' with message 'test.server.com:27017: unauthorized db:database_test ns:database_test.options lock type:0 client:127.0.0.1' in /apps/test_app/libs/Shanty/Mongo/Collection.php:3501
If I add user to my database_test all work fine.
<?php
/* Configure logging */
MongoLog::setModule( MongoLog::ALL );
MongoLog::setLevel( MongoLog::ALL );
$m = new MongoClient(); // connect
$db = $m->selectDB("database_test");
$db->authenticate('admin','12345');
this code work fine even if I add user to both admin and database_test.
Maybe someone has similar problem and know what I need to do.
First of all, you should use the following syntax for specifying authentication:
<?php
$m = new MongoClient("mongodb://admin:12345#localhost/database_test");
$db = $m->database_test;
It's a bit difficult to answer your question though, as "when I add user to this database" is not really descriptive. In order to get a proper answer, you need to learn to list the exact steps or code that you used to do this.
I am thinking that you were trying to auth against a normal database (database_test), where you would only have a user/pass set for the admin database. In that case, you need to auth to the admin database, and then select your database_test:
<?php
$m = new MongoClient("mongodb://admin:12345#localhost/admin");
$db = $m->database_test;
Thank you for your answer I figured out this.
Maybe it's will be heplful for some one on future, Shanty-Mongo require username, password and port in array of servers.
It's should looks like:
; Shanty Mongo Config
hosts.0.host = '127.0.0.1'
hosts.0.port = '27017'
hosts.0.username = 'root'
hosts.0.password = 'pass'
hosts.1.host = '127.0.0.1'
hosts.1.port = '27018'
hosts.1.username = 'root'
hosts.1.password = 'pass'
hosts.2.host = '127.0.0.1'
hosts.2.port = '27019'
hosts.2.username = 'root'
hosts.2.password = 'pass'
database = 'database_test'
replicaSet = true
Also what I do:
in mongo:
1. edit config file, enable auth (auth = true)
2. create user in admin database
3. connect as new user
4. create user in target database
in ZF config
update config file, as I describe above.
Also some times I get error: Fatal error: php_network_getaddresses, I think it's because I have some trouble with DNS or php trying resolve address: mongo://root:pass#127.0.0.1:27017,root:pass#127.0.0.1:27018,root:pass#127.0.0.1:27019/database_test

How can I confirm PHP MongoDB connection is properly recognizing replica sets?

Using the example from the manual:
$mongo = new Mongo("mongodb://sf2.example.com,ny1.example.com", array("replicaSet" => "myReplSet"));
When I check $mongo, it says it is indeed connected. I thought I could then call $mongo->isMaster() to get replica set details, but that doesn't work. Is that not a proper way of doing this?
isMaster isn't a PHP function (see http://www.php.net/manual/en/class.mongo.php for a list of functions available in the Mongo class). You can do:
$result = $mongo->myDb->command(array("isMaster" => 1));
This runs the isMaster command on the myDb database (it doesn't matter what db you run it on).

Categories