Using MongoDB with Core PHP: A Guide to Building Dynamic Web Applications

Haziq Ali
4 min readAug 13, 2023

--

MongoDB with PHP

In the world of web development, databases play a pivotal role in storing and managing data. MongoDB, a popular NoSQL database, offers a flexible and scalable solution for handling vast amounts of data. When combined with Core PHP, MongoDB opens up new possibilities for creating dynamic and data-driven web applications. In this tutorial, we’ll explore the integration of MongoDB with Core PHP and guide you through the process of building powerful web applications.

Prerequisites

Before we dive into the tutorial, ensure you have the following prerequisites in place:

  • Basic understanding of PHP programming.
  • MongoDB installed and running on your machine or server.
  • PHP MongoDB extension installed.
  • Composer installed.

Setting Up the Environment

Installing MongoDB

If you haven’t installed MongoDB yet, visit the official MongoDB website (https://www.mongodb.com/try/download/community) to download and install the appropriate version for your operating system.

Installing PHP MongoDB Extension

To work with MongoDB using Core PHP, you’ll need to install the PHP MongoDB extension. You can install it using the following command:

pecl install mongodb

Once the extension is installed, make sure to add extension=mongodb.so to your php.ini configuration file.

Note:

This was the part I faced a lot of problems with in the beginning. Let’s dive deep into it.

If pecl command doesn’t work. You can set up mongodb extension manually as well.

  1. Download PHP MongoDB driver.
  2. Extract php_mongo zip file
  3. Put php_mongodb.dll into the php\ext folder.
  4. Open php.ini file
  5. Write extension=mongodb just like line 31 in “Dynamic Extension” column.
reference for php ini file

Composer

A Dependency Manager for PHP

Create Project

For this tutorial, we will be performing CRUD operations, so you can name your project php-crud-mongodb or anything.

Installing MongoDB Package

We will install MongoDB package in our project to make connection with our local MongoDB server and perform CRUD operations on it.

composer install mongodb

This will add mongodb package in your newly created vendor folder.

Connecting to MongoDB

We will take an object oriented approach for this tutorial.

Create crud.php file.

To establish a connection to the MongoDB database using Core PHP, follow these steps:

<?php
namespace ;

require_once('vendor/autoload.php');

use MongoDB\Client;

class Crud
{
protected $client;
protected $collection;

function __construct()
{
$this->client = new Client('mongodb://localhost:27017/');
$this->collection = $this->client->selectCollection('databaseName', 'tableName/clusterName');
}

// rest of the code
}
?>

Replace "mongodb://localhost:27017" with the appropriate MongoDB server URI and "your_database_name" and "your_cluster_name"with the name of your MongoDB database.

CRUD Operations with MongoDB and Core PHP

Creating Documents

To insert data into MongoDB using Core PHP, use the insertOne() and insertMany() methods:

public function createDocument($data)
{
$this->collection->insertOne($data);
}

Reading Documents

Retrieve data from MongoDB using Core PHP with the find() method:

public function readDocument($filter)
{
return $this->collection->find($filter);
}

Updating Documents

Update existing documents in MongoDB using Core PHP’s updateOne() and updateMany() methods:

public function updateDocument($filter, $updateData)
{
$this->collection->updateOne($filter, ['$set' => $updateData]);
}

Deleting Documents

Remove documents from MongoDB collections using Core PHP’s deleteOne() and deleteMany() methods:

public function deleteDocument($filter)
{
$this->collection->deleteOne($filter);
}

Example Usage

This is an example of how you can use this class:

<?php

// Example usage
$crud = new Crud();

// Create a document
$newDocument = ['title' => 'New Post', 'content' => 'This is a new post.'];
$crud->createDocument($newDocument);

// Read documents
$documents = $crud->readDocument([]);
foreach ($documents as $document) {
// Process and display document data
}

// Update a document
$updateFilter = ['title' => 'New Post'];
$updateData = ['content' => 'Updated content'];
$crud->updateDocument($updateFilter, $updateData);

// Delete a document
$deleteFilter = ['title' => 'New Post'];
$crud->deleteDocument($deleteFilter);

?>

Indexing and Performance Optimization

Creating indexes in MongoDB can significantly improve query performance. Use the createIndex() method in Core PHP:

<?php
$collection->createIndex(['title' => 1]);
?>

Error Handling and Exception Management

When working with MongoDB and Core PHP, handle errors and exceptions gracefully:

<?php
try {
// MongoDB operations
} catch (MongoDB\Driver\Exception\Exception $e) {
echo "An error occurred: " . $e->getMessage();
}
?>

Security Considerations

Ensure the security of your MongoDB instance by enabling authentication, authorization, and following best practices.

Conclusion

Integrating MongoDB with Core PHP empowers you to build dynamic and scalable web applications. With the ability to perform CRUD operations, optimize performance, and handle errors effectively, you’re well-equipped to create powerful data-driven solutions. By combining the flexibility of MongoDB with the versatility of Core PHP, you’ll be prepared to tackle a wide range of web development projects.

You can use this file with your existing projects and new projects using ajax calls or simple php functions.

Remember, this tutorial is just the beginning. Explore the MongoDB documentation (https://docs.mongodb.com/) and experiment with different features to expand your skills further. Happy coding!

Additional Resources

--

--