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: / 4
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!

 

 
top_java_jobs Social photo sharing website in scala / lift by kramer: Keywords: scala, lift, tomcat, mongodb Th... http://t.co/jHmYqOzm #Java #Jobs
by top_java_jobs. Link: twitterfeed
plopezFr RT @mongodb: Rejoignez nous le 14 Juin pour MongoDB Paris. La plupart des présentations seront en français ! http://t.co/iX8EHOPV
by plopezFr. Link: Buffer
imjuni RT @kikikiblue: 이번엔 node.js와 mongodb 기반으로 실시간 웹앱을 쉽게 만들어주는 http://t.co/x0IgA2bQ 직접 자신의 서버 배포까지 해결해주는군요.
by imjuni. Link: web
Stiivi RT @michaelklishin: So yes indeed, MongoDB is now just a feature in PostgreSQL 9.2 beta, thanks to just a few functions by @tobyhede https://t.co/SUt9FoGo
by Stiivi. Link: Twitter for Mac

Google AdSense


Coffee and Cream Publishing