In our previous article titled “Installing and configuring php mongo driver with Apache in Ubuntu 12.04 LTS“, we have seen, how to install and configure php-mongo driver to connect to a MongoDB database from php.
In this article, we will create a PHP program to connect to a MongoDB database by authenticating user name with password using MongoClient api.
1. Prerequisites for this PHP application
- A web server with PHP and php-mongo driver installed
- A MongoDB server with or with out authentication enabled
2. Create a file namely mongodemo.php in the document root of the web server with the given below php code
<?php /** User name : admu Password : new_pass MongoDB host : localhost MongoDB port : 27017 Database : university */ $server = "mongodb://admu:new_pass@localhost:27017/university"; /** Remove username and password, if you want to connect to an unauthenticated MongoDB database. See the example code below */ // $server = "mongodb://localhost:27017/university"; // Connecting to server $c = new MongoClient( $server ); if($c->connected) echo "Connected successfully"; else echo "Connection failed"; ?>
3. Code in Action
Open the php file namely “mongodemo.php” using its url in a web browser. If the connection to the MongoDB server is established successfully, then a page similar to the given below will be displayed.
What is next?
An extension to this article is available at “A PHP program to insert individual and batch data into MongoDB database”
I am George Mathew, working as software architect and Android app developer at wptrafficanalyzer.in
You can hire me on hourly basis or on project basis for Android applications development.
For hiring me, please mail your requirements to email@example.com.
My other blogs