simple step-by-step Product CRUD example using PHP + MongoDB, suitable for learning/practical work

1. Install the requirements

You need:

  • XAMPP
  • PHP 8.2
  • MongoDB Server
  • MongoDB PHP Extension (mongodb)
  • Composer
  • MongoDB PHP Library

You can verify PHP:

php -v

Check whether MongoDB extension is enabled:

php -m | findstr mongodb

If it shows:

mongodb

the extension is installed correctly.


2. Create the project

Inside XAMPP:

C:\xampp\htdocs\

Create:

product_mongodb

Project structure:

product_mongodb/
│
├── vendor/
├── config.php
├── index.php
├── insert.php
├── edit.php
├── update.php
└── delete.php

3. Install MongoDB PHP Library

Open Command Prompt in the project folder:

cd C:\xampp\htdocs\product_mongodb

Run:

composer require mongodb/mongodb

Composer will create the vendor folder.

if error than

Step 1 — Open the correct php.ini

Open:

C:\xampp\php\php.ini

Search for:

;extension=zip

Change it to:

extension=zip

Also make sure MongoDB is enabled. Search for:

extension=mongodb

If it exists and is commented:

;extension=mongodb

4. Create MongoDB database

Start MongoDB server.

Then open MongoDB Shell (mongosh):

mongosh

Create/use database:

use productdb

You don’t actually need to manually create the database or collection. MongoDB will create them when the first product is inserted.


5. Create config.php

This file connects PHP to MongoDB.

<?php

require 'vendor/autoload.php';

try {

    $client = new MongoDB\Client("mongodb://localhost:27017");

    $database = $client->productdb;

    $collection = $database->products;

    echo "MongoDB Connected Successfully";

} catch (Exception $e) {

    echo "Connection Failed: " . $e->getMessage();

}

?>

Test it:

http://localhost/product_mongodb/config.php

You should see:

MongoDB Connected Successfully

6. Insert Product

Create insert.php:

<?php

require 'vendor/autoload.php';

$client = new MongoDB\Client("mongodb://localhost:27017");

$db = $client->productdb;

$products = $db->products;

if ($_SERVER["REQUEST_METHOD"] == "POST") {

    $name = $_POST['name'];
    $price = (float)$_POST['price'];
    $quantity = (int)$_POST['quantity'];

    $result = $products->insertOne([
        "name" => $name,
        "price" => $price,
        "quantity" => $quantity
    ]);

    echo "Product inserted successfully!";

}
?>

<!DOCTYPE html>
<html>
<head>
    <title>Add Product</title>
</head>

<body>

<h2>Add Product</h2>

<form method="post">

    Product Name:
    <input type="text" name="name" required>
    <br><br>

    Price:
    <input type="number" name="price" required>
    <br><br>

    Quantity:
    <input type="number" name="quantity" required>
    <br><br>

    <input type="submit" value="Add Product">

</form>

<br>

<a href="index.php">View Products</a>

</body>
</html>

Open:

http://localhost/product_mongodb/insert.php

Example:

Product Name: Laptop
Price: 55000
Quantity: 10

MongoDB document:

{
    name: "Laptop",
    price: 55000,
    quantity: 10
}

7. Display Products

Create index.php:

<?php

require 'vendor/autoload.php';

$client = new MongoDB\Client("mongodb://localhost:27017");

$db = $client->productdb;

$products = $db->products;

$result = $products->find();

?>

<!DOCTYPE html>
<html>

<head>

<title>Product List</title>

</head>

<body>

<h2>Product List</h2>

<a href="insert.php">Add Product</a>

<br><br>

<table border="1" cellpadding="10">

<tr>

    <th>ID</th>
    <th>Name</th>
    <th>Price</th>
    <th>Quantity</th>
    <th>Action</th>

</tr>

<?php

foreach ($result as $product) {

?>

<tr>

<td>
<?php echo $product['_id']; ?>
</td>

<td>
<?php echo $product['name']; ?>
</td>

<td>
<?php echo $product['price']; ?>
</td>

<td>
<?php echo $product['quantity']; ?>
</td>

<td>

<a href="edit.php?id=<?php echo $product['_id']; ?>">
Edit
</a>

&nbsp;

<a href="delete.php?id=<?php echo $product['_id']; ?>"
onclick="return confirm('Are you sure?')">
Delete
</a>

</td>

</tr>

<?php

}

?>

</table>

</body>

</html>

Now visit:

http://localhost/product_mongodb/index.php

You should see your products.


8. Update Product

Create edit.php:

<?php

require 'vendor/autoload.php';

$client = new MongoDB\Client("mongodb://localhost:27017");

$db = $client->productdb;

$products = $db->products;

$id = new MongoDB\BSON\ObjectId($_GET['id']);

$product = $products->findOne([
    '_id' => $id
]);

?>

<!DOCTYPE html>

<html>

<head>

<title>Edit Product</title>

</head>

<body>

<h2>Edit Product</h2>

<form action="update.php" method="post">

<input type="hidden"
       name="id"
       value="<?php echo $product['_id']; ?>">

Product Name:

<input type="text"
       name="name"
       value="<?php echo $product['name']; ?>">

<br><br>

Price:

<input type="number"
       name="price"
       value="<?php echo $product['price']; ?>">

<br><br>

Quantity:

<input type="number"
       name="quantity"
       value="<?php echo $product['quantity']; ?>">

<br><br>

<input type="submit" value="Update Product">

</form>

</body>

</html>

9. Create update.php

<?php

require 'vendor/autoload.php';

$client = new MongoDB\Client("mongodb://localhost:27017");

$db = $client->productdb;

$products = $db->products;

$id = new MongoDB\BSON\ObjectId($_POST['id']);

$name = $_POST['name'];

$price = (float)$_POST['price'];

$quantity = (int)$_POST['quantity'];

$products->updateOne(

    ['_id' => $id],

    [
        '$set' => [
            'name' => $name,
            'price' => $price,
            'quantity' => $quantity
        ]
    ]

);

header("Location: index.php");

exit;

?>

10. Delete Product

Create delete.php:

<?php

require 'vendor/autoload.php';

$client = new MongoDB\Client("mongodb://localhost:27017");

$db = $client->productdb;

$products = $db->products;

$id = new MongoDB\BSON\ObjectId($_GET['id']);

$products->deleteOne([
    '_id' => $id
]);

header("Location: index.php");

exit;

?>

CRUD operations

OperationPHP/MongoDB method
CreateinsertOne()
Readfind() / findOne()
UpdateupdateOne()
DeletedeleteOne()

MongoDB structure

productdb
   |
   └── products
        |
        ├── _id
        ├── name
        ├── price
        └── quantity

If you want the same Product CRUD example using MongoDB\Driver\Manager instead of MongoDB\Client, you can do it using the lower-level MongoDB PHP Driver.

Important: MongoDB\Driver\Manager comes from the PHP MongoDB extension, not from the Composer mongodb/mongodb library. So php --ri mongodb must work first.

1. Check MongoDB extension

Run:

php --ri mongodb

You should see something like:

MongoDB extension version => 1.x.x

Then:

php -m | findstr /i mongodb

Expected:

mongodb

2. Product Database Structure

We’ll use:

Database:  productdb
Collection: products

A product document will look like:

{
    _id: ObjectId("..."),
    name: "Laptop",
    price: 55000,
    quantity: 10
}

3. MongoDB Manager Connection

Create:

config.php
<?php

try {

    $manager = new MongoDB\Driver\Manager(
        "mongodb://localhost:27017"
    );

    echo "MongoDB Connected Successfully";

} catch (MongoDB\Driver\Exception\Exception $e) {

    echo "Connection Failed: " . $e->getMessage();

}

?>

Run:

http://localhost/product_mongodb/config.php

You should get:

MongoDB Connected Successfully

4. Insert Product

Create:

insert.php
<?php

$manager = new MongoDB\Driver\Manager(
    "mongodb://localhost:27017"
);

if ($_SERVER["REQUEST_METHOD"] == "POST") {

    $name = $_POST["name"];
    $price = (float) $_POST["price"];
    $quantity = (int) $_POST["quantity"];

    $bulk = new MongoDB\Driver\BulkWrite();

    $bulk->insert([
        "name" => $name,
        "price" => $price,
        "quantity" => $quantity
    ]);

    try {

        $result = $manager->executeBulkWrite(
            "productdb.products",
            $bulk
        );

        echo "Product inserted successfully!";

    } catch (MongoDB\Driver\Exception\Exception $e) {

        echo "Error: " . $e->getMessage();

    }
}

?>

<!DOCTYPE html>
<html>

<head>
    <title>Add Product</title>
</head>

<body>

<h2>Add Product</h2>

<form method="post">

    Product Name:
    <input type="text" name="name" required>

    <br><br>

    Price:
    <input type="number" name="price" required>

    <br><br>

    Quantity:
    <input type="number" name="quantity" required>

    <br><br>

    <input type="submit" value="Add Product">

</form>

<br>

<a href="index.php">View Products</a>

</body>

</html>

Important Manager concept

The main code is:

$bulk = new MongoDB\Driver\BulkWrite();

$bulk->insert([
    "name" => $name,
    "price" => $price,
    "quantity" => $quantity
]);

$manager->executeBulkWrite(
    "productdb.products",
    $bulk
);

5. Display Products

Create:

index.php
<?php

$manager = new MongoDB\Driver\Manager(
    "mongodb://localhost:27017"
);

$query = new MongoDB\Driver\Query([]);

try {

    $rows = $manager->executeQuery(
        "productdb.products",
        $query
    );

} catch (MongoDB\Driver\Exception\Exception $e) {

    die("Error: " . $e->getMessage());

}

?>

<!DOCTYPE html>

<html>

<head>

<title>Product List</title>

</head>

<body>

<h2>Product List</h2>

<a href="insert.php">Add Product</a>

<br><br>

<table border="1" cellpadding="10">

<tr>

    <th>ID</th>
    <th>Name</th>
    <th>Price</th>
    <th>Quantity</th>
    <th>Action</th>

</tr>

<?php

foreach ($rows as $product) {

?>

<tr>

<td>
<?php echo $product->_id; ?>
</td>

<td>
<?php echo $product->name; ?>
</td>

<td>
<?php echo $product->price; ?>
</td>

<td>
<?php echo $product->quantity; ?>
</td>

<td>

<a href="edit.php?id=<?php echo $product->_id; ?>">
Edit
</a>

|

<a href="delete.php?id=<?php echo $product->_id; ?>"
   onclick="return confirm('Delete this product?');">
Delete
</a>

</td>

</tr>

<?php

}

?>

</table>

</body>

</html>

Here we use:

new MongoDB\Driver\Query([])

and:

$manager->executeQuery()

to retrieve documents.


6. Edit Product

Create:

edit.php
<?php

$manager = new MongoDB\Driver\Manager(
    "mongodb://localhost:27017"
);

$id = new MongoDB\BSON\ObjectId($_GET["id"]);

$filter = [
    "_id" => $id
];

$query = new MongoDB\Driver\Query($filter);

$rows = $manager->executeQuery(
    "productdb.products",
    $query
);

$product = current($rows);

?>

<!DOCTYPE html>

<html>

<head>

<title>Edit Product</title>

</head>

<body>

<h2>Edit Product</h2>

<form action="update.php" method="post">

<input type="hidden"
       name="id"
       value="<?php echo $product->_id; ?>">

Product Name:

<input type="text"
       name="name"
       value="<?php echo $product->name; ?>"
       required>

<br><br>

Price:

<input type="number"
       name="price"
       value="<?php echo $product->price; ?>"
       required>

<br><br>

Quantity:

<input type="number"
       name="quantity"
       value="<?php echo $product->quantity; ?>"
       required>

<br><br>

<input type="submit"
       value="Update Product">

</form>

</body>

</html>

7. Update Product

Create:

update.php
<?php

$manager = new MongoDB\Driver\Manager(
    "mongodb://localhost:27017"
);

$id = new MongoDB\BSON\ObjectId(
    $_POST["id"]
);

$name = $_POST["name"];

$price = (float) $_POST["price"];

$quantity = (int) $_POST["quantity"];

$bulk = new MongoDB\Driver\BulkWrite();

$bulk->update(

    [
        "_id" => $id
    ],

    [
        '$set' => [
            "name" => $name,
            "price" => $price,
            "quantity" => $quantity
        ]
    ]

);

try {

    $manager->executeBulkWrite(
        "productdb.products",
        $bulk
    );

    header("Location: index.php");

    exit;

} catch (MongoDB\Driver\Exception\Exception $e) {

    echo "Update Error: " . $e->getMessage();

}

?>

8. Delete Product

Create:

delete.php
<?php

$manager = new MongoDB\Driver\Manager(
    "mongodb://localhost:27017"
);

$id = new MongoDB\BSON\ObjectId(
    $_GET["id"]
);

$bulk = new MongoDB\Driver\BulkWrite();

$bulk->delete([
    "_id" => $id
]);

try {

    $manager->executeBulkWrite(
        "productdb.products",
        $bulk
    );

    header("Location: index.php");

    exit;

} catch (MongoDB\Driver\Exception\Exception $e) {

    echo "Delete Error: " . $e->getMessage();

}

?>

9. Complete Project

Your folder will be:

product_mongodb/
│
├── config.php
│
├── index.php
│
├── insert.php
│
├── edit.php
│
├── update.php
│
└── delete.php

No Composer library is required for this version if the MongoDB PHP extension is installed.


10. Manager CRUD Methods

For your students, the important part is this:

OperationMongoDB Manager class
ConnectionMongoDB\Driver\Manager
Insert/Update/DeleteMongoDB\Driver\BulkWrite
ReadMongoDB\Driver\Query
Execute Read$manager->executeQuery()
Execute Write$manager->executeBulkWrite()
IDMongoDB\BSON\ObjectId

Simple flow

PHP
 │
 ▼
MongoDB\Driver\Manager
 │
 ├── executeQuery()
 │       │
 │       └── Read Products
 │
 └── executeBulkWrite()
         │
         ├── insert()
         ├── update()
         └── delete()

Most important connection line

$manager = new MongoDB\Driver\Manager(
    "mongodb://localhost:27017"
);

This is the MongoDB Manager approach, unlike the previous example:

$client = new MongoDB\Client(
    "mongodb://localhost:27017"
);

For your current setup, Manager is a good choice for teaching the MongoDB PHP Driver directly, because students can clearly see Manager, Query, BulkWrite, and ObjectId classes.

By admin