Introduction

In this guide, you'll learn how to create a simple CRUD (Create, Read, Update, Delete) application using MongoDB as your NoSQL database and PHP as your server-side scripting language. We'll cover the basics of MongoDB, setting up a PHP environment, and building a web application that can perform CRUD operations. Sample code and examples will help you get started.


Prerequisites

Before you begin, make sure you have the following prerequisites:

  • A web server with PHP installed. You can use XAMPP, WAMP, or a similar tool for local development.
  • MongoDB installed and running locally or accessible through a connection string.
  • A code editor for writing PHP scripts and web pages.
  • The MongoDB PHP driver installed. You can install it using
    composer require mongodb/mongodb
    .

Step 1: Connecting to MongoDB

Begin by connecting your PHP application to MongoDB. You'll need to specify the connection URL and database name. Here's an example:

require 'vendor/autoload.php';
use MongoDB\Client;
// MongoDB connection URL
$uri = "mongodb://localhost:27017";
// Connect to the MongoDB server
$client = new Client($uri);
// Choose a database (replace 'mydb' with your database name)
$database = $client->mydb;
?>

Step 2: Creating the CRUD Application

Create your PHP application to perform CRUD operations on MongoDB. Here's an example of creating a simple web page for adding and displaying data:

    CRUD Application with MongoDB and PHP

CRUD Application with MongoDB and PHP


// Create operation
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$collection = $database->mycollection;
$data = [
'name' => $_POST['name'],
'email' => $_POST['email']
];
$result = $collection->insertOne($data);
echo 'Document added with ID: ' . $result->getInsertedId();
}
?>

Add a New Document




Documents

$collection = $database->mycollection;
$cursor = $collection->find();
foreach ($cursor as $document) {
echo 'Name: ' . $document['name'] . ' | Email: ' . $document['email'] . '
';
}
?>