Using MongoDB in PHP on Windows.

Now you would think that in this day and age I wouldn't need to write and article about this, but you would be wrong. Let's say that you're on Windows and you want to install an Apache Web Server. Well, Apache is mostly provided as source code or binaries, thus you will have to rely on third parties like either Xampp or Wamp. If you're on Linux, installation is a breeze, as you'd install the httpd service via a terminal. Chances are you won't even know there were any issues, but for many different reasons, set up in windows was definitely very confusing.

Sadly, your troubles begin with the fact that the most recent version of the MongoDB PHP driver for windows is 1.13.0 and is a year behind the Linux version 1.15.1. Add to the fact that most of the previous documentation online as well as tutorials for using MongoDB are for an older Mongo Driver and things go south very fast. You might try to use PECL or PEAR commands to install and configure the driver, but those two contain classes that contain code that was depreciated in PHP8. So tough luck you can't use either. So you need to go to the PECL site and manually download a compatible driver DLL. Then extract the downloaded DLL from its zip file and copy/paste to the ext folder inside your PHP installation. Finally list the driver as an extension in the PHP.ini file.

After restarting the Apache Server. You can confirm that the driver has been installed by using

<?php phpinfo() ?>

 inside of a PHP file. Once confirmed, here is where the next level of confusion begins. As I said before, even the MongoDB site has yet to catch up to PHP.net documentation. Thus the connection code provided

$client = new MongoDB\Client(<connection string>);

has been depreciated. Other sources (Stack Overflow) may suggest using

$client = new MongoClient(<connection string>); 

but this as well has been depreciated. The correct syntax is to use is

$manager = new MongoDB\Driver\Manager(<connection string>);

This creates a manager object that connects to your MongoDB. From here you can use other commands such as

$query = new MongoDB\Driver\Query($filter, $options);
$manager->executeQuery('db_name.my_collection', $query)
 

which will return a result set from a collection. Full documentation is available at https://www.php.net/manual/en/book.mongodb.php

 

 


Post a Comment

Previous Post Next Post