vijay venkat
vijay venkat

Reputation: 81

how to connect to mongodb database in php 7

I am using mongodb 3.2 and php 7 I have installed the driver and its working.. Here is my code

<?php
$client = new MongoDB\Driver\Manager();
$db = $client->selectDatabase('inventory');
?>

how to connect to database "inventory" the error that comes is

Fatal error: Uncaught Error: Call to undefined method MongoDB\Driver\Manager::selectDatabase() 

Upvotes: 3

Views: 5181

Answers (1)

b01
b01

Reputation: 4384

I don't think you want to call the Manager directly. The newer MongoDB extension that replaces the built-in PHP Mongo DB client; You need to have the following requirements for the code to work. The code example that follows assumes the following:

  1. You load with the composer autoloader.
  2. You have the new MongoDB Driver extension from here: http://php.net/manual/en/set.mongodb.php
  3. That you use the composer MongoDB Client library from here: http://php.net/manual/en/mongodb.tutorial.library.php
  4. PHP >=5.6

use MongoDB\Client as MongoDbClient;
// When auth is turned on, then pass in these as the second parameters to the client.
$options = [
    'password' => '123456',
    'username' => 'superUser',
];

try {
    $mongoDbClient = new MongoDbClient('mongodb://localhost:27017');
} catch (Exception $error) {
    echo $error->getMessage(); die(1);
}

// This will get or make (in case it does not exist) the inventory database
// and a collection beers in the Mongo DV server.
$collection = $mongoDbClient->inventory->beers;

$collection->insertOne( [ 'name' => 'Hinterland', 'brewery' => 'BrewDog' ] );

$result = $collection->find( [ 'name' => 'Hinterland', 'brewery' => 'BrewDog' ] );

foreach ($result as $entry) {
    echo $entry['_id'], ': ', $entry['name'], "\n";
}

Upvotes: 2

Related Questions