How to use mongoDB in Codeigniter with example

In previous articles, we discussed what is MongoDB, why it the most used database with its benefits and drawbacks. And also on how to install MongoDB and connect it with PHP. To know more about these articles please refer below links.

What is MongoDB? Benefits and drawbacks

How to install MongoDB on windows and connect it with PHP 7

Today we are going to discuss MongoDB with Codeigniter.we are going to do this in a few simple steps.

STEP 1 : 

Download a fresh Codeigniter from the official website https://codeigniter.com/download. Create a file named mongo_db.php in the config folder of the application and paste the below code which creates a database connection for MongoDB.

 

<?php if ( ! defined(‘BASEPATH’)) exit(‘No direct script access allowed’);
/*
| ————————————————————————-
| DATABASE CONNECTIVITY SETTINGS
| ————————————————————————-
| This file will contain the settings needed to access your Mongo database.
|
|
| ————————————————————————
| EXPLANATION OF VARIABLES
| ————————————————————————
|
| [‘hostname’] The hostname of your database server.
| [‘username’] The username used to connect to the database
| [‘password’] The password used to connect to the database
| [‘database’] The name of the database you want to connect to
| [‘db_debug’] TRUE/FALSE – Whether database errors should be displayed.
| [‘write_concerns’] Default is 1: acknowledge write operations. ref(http://php.net/manual/en/mongo.writeconcerns.php)
| [‘journal’] Default is TRUE : journal flushed to disk. ref(http://php.net/manual/en/mongo.writeconcerns.php)
| [‘read_preference’] Set the read preference for this connection. ref (http://php.net/manual/en/mongoclient.setreadpreference.php)
| [‘read_preference_tags’] Set the read preference for this connection. ref (http://php.net/manual/en/mongoclient.setreadpreference.php)
|
| The $config[‘mongo_db’][‘active’] variable lets you choose which connection group to
| make active. By default there is only one group (the ‘default’ group).
|
*/

$config[‘mongo_db’][‘active’] = ‘default’;
$config[‘mongo_db’][‘default’][‘no_auth’] = FALSE;
$config[‘mongo_db’][‘default’][‘hostname’] = ‘localhost’;
$config[‘mongo_db’][‘default’][‘port’] = ‘27017’;
$config[‘mongo_db’][‘default’][‘username’] = ‘yourdbusername’;
$config[‘mongo_db’][‘default’][‘password’] = ‘yourdbpassword’;
$config[‘mongo_db’][‘default’][‘database’] = ‘yourdatabasename’;
$config[‘mongo_db’][‘default’][‘db_debug’] = TRUE;
$config[‘mongo_db’][‘default’][‘return_as’] = ‘array’;
$config[‘mongo_db’][‘default’][‘write_concerns’] = (int)1;
$config[‘mongo_db’][‘default’][‘journal’] = TRUE;
$config[‘mongo_db’][‘default’][‘read_preference’] = ‘primary’;
$config[‘mongo_db’][‘default’][‘read_concern’] = ‘local’; //’local’, ‘majority’ or ‘linearizable’
$config[‘mongo_db’][‘default’][‘legacy_support’] = TRUE;

 

STEP 2 : 

Create another file named mongo_db.php in the libraries folder of the application and copy the code from the below link.

https://github.com/TejaswiReddy2/phpmongocodeiniter/blob/master/application/libraries/Mongo_db.php

Now the connection is done. Let’s execute some queries to check if the connection is set properly or not.

Start your mongo and xampp server, if you are not sure about how to start you can read my previous articles. Firstly we need to create a DB, follow the process one by one and enter (copy the code which is in green color).

show dbs                                                                   =        Shows all your database

use mongo_codeigniter                                         =        Creates DB with name mongo_codeigniter if it doesn’t exist.

show users                                                               =        Shows users created.

db.createUser( { user: “yourdbusername”, pwd: “yourdbpassword”, roles: [ { role: “dbOwner”, db: “yourdbname” } ] } )

You can enter your preferred username and password and your database name in which you want to create user.i.e here we use mongo_codeigniter as DB so enter it in place of yourdbname.

Database creation is done, now let’s write query to insert data from PHP file.

Open your welcome.php file in the controller and paste the below code.

 

<?php
defined(‘BASEPATH’) OR exit(‘No direct script access allowed’);

class Welcome extends CI_Controller {

public function __construct()
{
parent:: __construct();
error_reporting(E_ALL ^ E_NOTICE);
$this->load->model(array(‘common_model’));
$this->load->library(‘mongo_db’);
}

public function index()
{
$param[‘userName’] = “VBloggers”;
$param[‘userEmail’] = “[email protected]”;
$data = $this->common_model->addData(‘inter_users’,$param);
if($data):
echo “Data inserted”;die;
else:
echo “Something went wrong”;die;
endif;
$this->load->view(‘welcome_message’);
}
}

Create a model named common_model.php and paste below function.

 

<?php
if(!defined(‘BASEPATH’)) exit(‘No direct script access allowed’);
class Common_model extends CI_Model
{
public function __construct()
{
parent::__construct();
}

/***********************************************************************
** Function name : addData
** Developed By : VBloggers
** Purpose : This function used for add data
** Date : 23 MAY 2020
************************************************************************/
public function addData($tableName=”,$param=array())
{
$last_insert_id = $this->mongo_db->insert($tableName,$param);
return $last_insert_id;
} // END OF FUNCTION
}

Data is inserted and you have successfully connected PHP and mongo. You can also download the source code from the below link.

Download SourceCode

Leave a Reply

Your email address will not be published. Required fields are marked *

The maximum upload file size: 2 MB. You can upload: image, document. Links to YouTube, Facebook, Twitter and other services inserted in the comment text will be automatically embedded.