PDO stands for PHP Data Objects, and it is a database access abstraction layer in PHP that provides a consistent way to interact with various databases, including MySQL, PostgreSQL, and SQLite. However, PDO does not support NoSQL databases like MongoDB natively.
To access MongoDB from PHP using PDO, you can follow these steps:
pecl install mongodb
php.ini
file and add the following line:extension=mongodb.so
// Replace the connection details with your own
$dsn = 'mongodb://username:password@localhost:27017';
$database = 'mydatabase';
$mongoClient = new MongoDB\Client($dsn);
$collection = $mongoClient->$database->mycollection;
Insert a document:
$document = ['name' => 'John Doe', 'age' => 25];
$collection->insertOne($document);
Fetch documents:
$documents = $collection->find();
foreach ($documents as $document) {
echo $document['name'] . ' ' . $document['age'] . "\n";
}
Update a document:
$filter = ['name' => 'John Doe'];
$update = ['$set' => ['age' => 30]];
$collection->updateOne($filter, $update);
Delete a document:
$filter = ['name' => 'John Doe'];
$collection->deleteOne($filter);
These are just a few examples of how to use PDO-like methods to interact with a MongoDB database from PHP. You can refer to the official MongoDB PHP Library documentation for more detailed usage instructions and available methods.