Database Reference
In-Depth Information
Figure 2-3. Displaying your MongoDB information in PHP
Once you confirm that the installation was successful and that the driver loaded successfully, you're ready to
write some PHP code and walk through a MongoDB example that leverages PHP.
Connecting to and Disconnecting from the PHP Driver
You've confirmed that the MongoDB PHP driver has been loaded correctly, so it's time to start writing some PHP code!
Let's take a look at two simple yet fundamental options for working with MongoDB: initiating a connection between
MongoDB and PHP, and then severing that connection.
You use the Mongo class to initiate a connection between MongoDB and PHP; this same class also lets you use the
database server commands. A simple yet typical connection command looks like this:
$connection = new Mongo();
If you use this command without providing any parameters, it will connect to the MongoDB service on the
default MongoDB port (27017) on your localhost. If your MongoDB service is running somewhere else, then you
simply specify the hostname of the remote host you want to connect to:
$connection = new Mongo(" example.com " );
This line instantiates a fresh connection for your MongoDB service running on the server and listening to the
example.com domain name (note that it will still connect to the default port: 27017). If you want to connect to a
different port number, however (for example, if you don't want to use the default port, or you're already running
another session of the MongoDB service on that port), you can do so by specifying the port number and hostname:
$connection = new Mongo(" example.com:12345 " );
 
Search WWH ::




Custom Search