0

How do I connect to a MongoDB database with the PHP driver extension?

I tried with localhost, and it works fine, but it needs to connect with the database to show the products.

<?php
class MongoDatabase{
public function connect(){
    //connection for local testing
    //$mng = new MongoDB\Driver\Manager("mongodb://localhost:27017");

    //connection for actual implementing and deploying
    $client = new MongoDB\Client("mongodb://localhost:27017");
    //$client = new MongoDB\Client("mongodb+srv://******:****@auctionmarket-dbs.adxht.mongodb.net/auctionmarket?retryWrites=true&w=majority");
   
    //echo "MongoDB connected <br>";
    return $client;
}

?>

When I connect it with mongodb server, I got this error:

Fatal error: Uncaught MongoDB\Driver\Exception\ConnectionTimeoutException: Failed to look up SRV record "_mongodb._tcp.auctionmarket-dbs.adxht.mongodb.net": A temporary error occurred on an authoritative name server. Try again later. in /Applications/MAMP/htdocs/MVP_auctionmarket/vendor/mongodb/mongodb/src/functions.php:440 Stack trace: #0 /Applications/MAMP/htdocs/MVP_auctionmarket/vendor/mongodb/mongodb/src/functions.php(440): MongoDB\Driver\Manager->selectServer(Object(MongoDB\Driver\ReadPreference)) #1 /Applications/MAMP/htdocs/MVP_auctionmarket/vendor/mongodb/mongodb/src/Collection.php(655): MongoDB\select_server(Object(MongoDB\Driver\Manager), Array) #2 /Applications/MAMP/htdocs/MVP_auctionmarket/mvc/models/ProductModel.php(30): MongoDB\Collection->find(Array, Array) #3 /Applications/MAMP/htdocs/MVP_auctionmarket/mvc/controllers/HomeController.php(10): ProductModel->findEndSoonProduct() #4 /Applications/MAMP/htdocs/MVP_auctionmarket/mvc/core/App.php(39): HomeController->index() #5 /Applications/MAMP/htdocs/MVP_aucti in /Applications/MAMP/htdocs/MVP_auctionmarket/vendor/mongodb/mongodb/src/functions.php on line 440 

This is my code:

<?php 
class MongoDatabase{
public function connect(){
    //connection for local testing
    //$mng = new MongoDB\Driver\Manager("mongodb://localhost:27017");

    //connection for actual implementing and deploying
    //$client = new MongoDB\Client("mongodb://localhost:27017");
    $client = new MongoDB\Client("mongodb+srv://*****:*****@auctionmarket-dbs.adxht.mongodb.net/auctionmarket?retryWrites=true&w=majority");
   
    //echo "MongoDB connected <br>";
    return $client;
}

The link to the database: mongodb+srv://******:*****8@auctionmarket-dbs.adxht.mongodb.net/auctionmarket?retryWrites=true&w=majority

SOLVED

I am using the MAMP default port which is the reason why it does not work. Just change it to 80 & 3306 to access the localhost with MongoDB.

0 Answers0