@scotty_walker
To connect to MongoDB using PHP, you can follow these steps:
1
|
$mongoClient = new MongoDBClient("mongodb://localhost:27017"); |
This code creates a new instance of the MongoDB client and connects it to a MongoDB server running on localhost at the default port 27017.
1
|
$database = $mongoClient->myDatabase; |
This code retrieves the "myDatabase" database from the MongoDB server and stores it in the $database variable.
1
|
$collection = $database->myCollection; |
This code retrieves the "myCollection" collection from the "myDatabase" database and stores it in the $collection variable.
1 2 3 4 5 |
$insertResult = $collection->insertOne([ 'name' => 'John Doe', 'age' => 30, 'email' => '[email protected]' ]); |
This code inserts a new document into the "myCollection" collection with the name, age, and email fields set to "John Doe", 30, and "[email protected]", respectively.
These are the basic steps to connect to MongoDB using PHP and perform CRUD operations. There are many other operations you can perform, such as querying, updating, and deleting documents. You can find more information in the official MongoDB PHP library documentation.
@scotty_walker
To connect to MongoDB using PHP, you need to follow these steps:
You can install the MongoDB PHP driver using PECL. To do this, run the following command:
1
|
pecl install mongodb |
Once you have installed the MongoDB PHP driver, you need to enable it by adding the following line to your php.ini file:
1
|
extension=mongodb.so
|
To create a connection to MongoDB, you can use the MongoDBClient
class. Here is an example:
1
|
$mongoClient = new MongoDBClient("mongodb://localhost:27017"); |
In this example, we are creating a connection to a MongoDB server running on the localhost and listening on the default port (27017).
Once you have created a connection to MongoDB, you can select a database by calling the selectDatabase
method on the $mongoClient
object. Here is an example:
1
|
$database = $mongoClient->selectDatabase("mydb"); |
In this example, we are selecting a database named mydb
.
Once you have selected a database, you can perform CRUD (Create, Read, Update, Delete) operations on its collections using the appropriate methods provided by the MongoDB PHP driver.
Here is an example of inserting a document into a collection:
1 2 3 |
$collection = $database->mycollection; $document = array("name" => "John", "age" => 30); $result = $collection->insertOne($document); |
In this example, we are inserting a document into a collection named mycollection
.
That's it! You have successfully connected to MongoDB using PHP and performed a CRUD operation.