Andy Jainson
Andy Jainson

Reputation: 95

MongoDb error with php 7 on xampp CodeIgniter

I am getting the following error when running the app in xampp with Php 7. I am new to mongoDb. Can't figure out what might solve this issue. Any help or suggestion about the problem will be highly appreciated. Thank you for your help. Below is the code I believe have some issue.

Error:

An uncaught Exception was encountered

Type: Error

Message: Class 'MongoClient' not found

Filename: C:\xampp\htdocs\Web\application\libraries\Mongo_db.php

Line Number: 49

Backtrace:

File: C:\xampp\htdocs\Web\application\controllers\Home.php Line: 7 Function: __construct

File: C:\xampp\htdocs\Web\index.php Line: 315 Function: require_once

libraries\Mongo_db.php

<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Mongo_db
{

        private $debug;
    private $write_concerns;
    private $journal;
    private $selects = array();
    private $updates = array();
    private $wheres = array();
    private $limit  = 999999;
    private $offset = 0;
    private $sorts  = array();
    private $return_as = 'array';
    public $benchmark = array();
    public function __construct()
    {

    //Check mongodb is installed in your server otherwise display an error
    /*if ( ! class_exists('Mongo') && ! class_exists('MongoClient'))
        {
            show_error("The MongoDB PECL extension has not been installed or enabled", 500);
        }*/
    if (!class_exists('MongoDB\Driver\Manager')) {
   show_error("The MongoDB PECL extension has not been installed or enabled", 500);
}

            //get instance of CI class
            if (function_exists('get_instance'))
            {
            $this->_ci = get_instance();
            }

            else
            {
            $this->_ci = NULL;
            }

//load the config file which we have created in 'config' directory
$this->_ci->load->config('mongodb');

$config='default';
// Fetch Mongo server and database configuration from config file which we have created in 'config' directory
$config_data = $this->_ci->config->item($config);

try{
//connect to the mongodb server
$this->mb = new MongoClient('mongodb://'.$config_data['mongo_hostbase']);

//select the mongodb database

$this->db=$this->mb->selectDB($config_data['mongo_database']);

}
catch (MongoConnectionException $exception)
{
//if mongodb is not connect, then display the error
show_error('Unable to connect to Database', 500);
}

}


/**
    * --------------------------------------------------------------------------------
    * Aggregation Operation
    * --------------------------------------------------------------------------------
    *
    * Perform aggregation on mongodb collection
    *
    * @usage : $this->mongo_db->aggregate('foo', $ops = array());
    */
    public function aggregate($collection, $operation)
    {
        if (empty($collection))
        {
            show_error("In order to retreive documents from MongoDB, a collection name must be passed", 500);
        }

        if (empty($operation) && !is_array($operation))
        {
            show_error("Operation must be an array to perform aggregate.", 500);
        }

        try
        {
            $documents = $this->db->{$collection}->aggregate($operation);
            //$this->_clear();

            if ($this->return_as == 'object')
            {
                return (object)$documents;
            }
            else
            {
                return $documents;
            }
        }
        catch (MongoResultException $e)
        {

            if(isset($this->debug) == TRUE && $this->debug == TRUE)
            {
                show_error("Aggregation operation failed: {$e->getMessage()}", 500);
            }
            else
            {
                show_error("Aggregation operation failed: {$e->getMessage()}", 500);
            }
        }
    }



}
?>

config/mongodb.php

<?php

//mongodb host
$config['default']['mongo_hostbase'] = 'localhost';
//mongodb name

$config['default']['mongo_database'] = 'appname';
//mongodb username - by default, it is empty
$config['default']['mongo_username'] = 'root';
//mongodb password - by default, it is empty
$config['default']['mongo_password'] = 'root';
?>

config/mongo.php

<?php
$config['mongo_server'] = 'localhost:27017';
$config['mongo_dbname'] = 'appname';
?>

Upvotes: 0

Views: 2158

Answers (2)

Channaveer Hakari
Channaveer Hakari

Reputation: 2927

Once you install MongoDB you cannot connect with PHP directly. You need to install the MongoDB Driver for PHP which you can find in the following URL

http://php.net/manual/en/mongodb.installation.php

Based on the type of the OS you can download the one.

Once your done with that. You can use the composer to download the mongo library so that you can start interacting with it

{
    "require": {
        "mongodb/mongodb": "^1.1"
    }
}

Once your done with that you will have a vendor directory in your project folder which contains the autoload.php which will handle auto loading of the necessary and dependency libraries required in Vendor.

You can start using the library as follows

db_connect.php

<?php
/* Require the Vendor for autoloading MongoDb Client */
include_once 'vendor/autoload.php';

/* Create the Object of Mongodb */
$mongoDB                = new MongoDB\Client;

/* Creating the database on which I will be working */
$erpDB          = $mongoDB->database_name;

You can use the above code as follows

products.php

<?php

include_once 'DB/db_connect.php';
/* The following creates the products collection */
$productsCollection     = $erpDB->products;

$insertedData       = $productsCollection->insertOne(
    ['_id' => $idCounter, 'product_name' => $productName, 'product_quantity' => $productQuantity]
);

Upvotes: 0

pspatel
pspatel

Reputation: 518

The MongoCLient class was provided by pecl install mongo. But pecl/mongo is not available for php7 and deprecated in favor of pecl/mongodb. But with pecl/mongodb you'll need to use MongoDB\Driver\Manager instead of MongoClient

Please see here for further reading.

Upvotes: 1

Related Questions