Joomla Jumpstart

  • Increase font size
  • Default font size
  • Decrease font size
Home NoSQL Databases MongoDB How to connect to MongoDB from PHP

How to connect to MongoDB from PHP

E-mail Print PDF
User Rating: / 5
PoorBest 

MongoDB logoMongoDB opens up a whole new level of opportunities for the PHP developer. Once you have the Mongo database setup and the Mongo PHP driver installed and activated, you need to write code to make a connection to the Mongo database. In PHP connecting to Mongo is as simple as connecting to a MySQL server.

 


To connect to the Mongo database, you need the URL (or IP Address) and a port.

First setup your connection string like this:

$url = 'localhost'; 
$port = 27017; 
$connStr = $url.':'.$port; 

If you have security enabled on Mongo, next add the authentication information:

$auth = empty($username)    ?    ''    :    "mongodb://{$username}:{$password}@";

Finally, make the connection:

$myConnection = new Mongo($auth.$connStr);

If you want to handle connection problems, wrap the connection in a try...catch block:

try {
     $myConnection = new Mongo($auth.$connStr);
} catch (Exception $e) {
    echo $e->getMessage();
}

No you have a connection to your Mongo database!

 

 
spara More geojson/simple feature type support in mongoDB 2.4 #foss4gna
by spara. Link: Tweetbot for Mac
MongoQuestion "Reference documents with ObjectId when saving in mongoose" #MongoDB - http://t.co/6JmahoIORY
by MongoQuestion. Link: Mongo Question
MongoQuestion "How to remove a "document" in MongoDB using MongoVUE?" #MongoDB - http://t.co/tz0knkVQku
by MongoQuestion. Link: Mongo Question
omarvr72 New Geo Features in MongoDB 2.4 - http://t.co/SKXpR5w2md #fb
by omarvr72. Link: Tweet Button


Coffee and Cream Publishing