PHP

Learn how to connect to MongoDB databases in Sealos DevBox using PHP

This guide will walk you through the process of connecting to a MongoDB database using PHP within your Sealos DevBox project.

Prerequisites

Install Required Extensions

In your Cursor terminal, ensure that the MongoDB extension for PHP is installed:

sudo pecl install mongodb

Install the MongoDB PHP Library

To install the MongoDB PHP Library, run the following command in your php-quickstart directory:

composer require mongodb/mongodb

Connection Setup

Create a Configuration File

First, let's create a configuration file to store our database connection parameters. Create a file named config.php in your project directory with the following content:

config.php
<?php
return [
    'host' => 'your_mongodb_host',
    'port' => '27017',
    'database' => 'your_database_name',
    'username' => 'your_username',
    'password' => 'your_password'
];

Replace the placeholders with your actual MongoDB credentials from the Database app in Sealos.

Create a Database Connection Function

Next, let's create a PHP file that will handle the database connection. Create a file named db_connect.php with the following content:

db_connect.php
<?php
require_once __DIR__ . '/vendor/autoload.php'; // Ensure you have the MongoDB PHP library installed
 
function getMongoDBConnection() {
    $config = include 'config.php';
    
    try {
        $client = new MongoDB\Client(
            "mongodb://{$config['username']}:{$config['password']}@{$config['host']}:{$config['port']}/{$config['database']}?authSource=admin"
        );
        echo "Connected successfully to MongoDB.\n";
        return $client->selectDatabase($config['database']);
    } catch (Exception $e) {
        die("Connection failed: " . $e->getMessage());
    }
}

This function reads the configuration from config.php and establishes a connection to the MongoDB database.

Create a Test Script

Now, let's create a test script to verify our connection and perform some basic database operations. Create a file named test_mongodb.php with the following content:

test_mongodb.php
<?php
require_once 'db_connect.php';
 
$db = getMongoDBConnection();
 
// Insert a document
$collection = $db->employees;
$insertResult = $collection->insertOne([
    'name' => 'John Doe',
    'position' => 'Developer'
]);
echo "Inserted document with ID: " . $insertResult->getInsertedId() . "\n";
 
// Find documents
$cursor = $collection->find();
echo "Employees:\n";
foreach ($cursor as $document) {
    echo "ID: " . $document['_id'] . ", Name: " . $document['name'] . ", Position: " . $document['position'] . "\n";
}
 
// Update a document
$updateResult = $collection->updateOne(
    ['name' => 'John Doe'],
    ['$set' => ['position' => 'Senior Developer']]
);
echo "Modified " . $updateResult->getModifiedCount() . " document(s)\n";
 
// Delete a document
$deleteResult = $collection->deleteOne(['name' => 'John Doe']);
echo "Deleted " . $deleteResult->getDeletedCount() . " document(s)\n";

Usage

To run the test script, use the following command in your Cursor terminal:

php test_mongodb.php

This will execute the script, demonstrating the connection to the database, document insertion, querying, updating, and deletion.

Best Practices

  1. Use environment variables or a separate configuration file for database credentials.
  2. Always handle potential errors using try-catch blocks.
  3. Use the MongoDB PHP library for better performance and features.
  4. Close the database connection after operations are complete (in this case, it's handled automatically).
  5. Use appropriate indexing for frequently queried fields to improve performance.

Troubleshooting

If you encounter connection issues:

  1. Verify your database credentials in the config.php file.
  2. Ensure your MongoDB database is running and accessible.
  3. Check for any network restrictions in your DevBox environment.
  4. Confirm that the MongoDB PHP extension is correctly installed.

For more detailed information on using MongoDB with PHP, refer to the official MongoDB PHP library documentation.

Edit on GitHub

Last updated on

On this page