Introduction

Here we will see Codeigniter MongoDB CRUD example, where CRUD means Create, Read, Update and Delete. So basically we will perform creating new user, reading users/user, update existing user and deleting existing user operations into MongoDB.

MongoDB is one of the widely used NoSQL(Not only SQL) database in market today. MongoDB is a document database with the scalability and flexibility that you want with the querying and indexing that you need. Often we come across a situation where we end up using MongoDB with PHP based framework Codeigniter.

Prerequisites

Apache 2.4, PHP 7.3.5, Codeigniter 3.1.10

Configure PHP 7.3.5 and MongoDB 4.0.10

Example Implementation

Creating Project Directory

We need to first create our root project directory in order to implement the Codeigniter multi-language website.

It’s assumed that you have setup Apache 2.4, PHP 7.3.5 and Codeigniter 3.1.10 in Windows system.

Next we will create a project root directory called codeIgniter-3.1.10-mongodb under the Apache server’s htdocs folder.

Now move all the directories and files from Codeigniter 3.1.10 framework into codeIgniter-3.1.10-mongodb directory.

We may not mention the project root directory in subsequent sections and we will assume that we are talking with respect to the project root directory.

Autoload Configuration

We need some configurations, such as, auto-loading for helpers to avoid loading every time we need to use.

$autoload['libraries'] = array('form_validation');
$autoload['helper'] = array('url');

Creating MongoDB Configurations

Create a config file to hold configurations for MongoDB server.

Create a file called mongodb.php under application/config folder with the below content into it.

You may have more configurations as per your need.

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

/*
* Author: https://www.roytuts.com
*/

$config['host'] = 'localhost';
$config['port'] = 27017;
$config['username'] = '';
$config['password'] = '';
$config['authenticate'] = FALSE;

Creating Library

We will create a library class in order to establish connection to MongoDB server.

Here we are going to create a simple class that just connects to the MongoDB server. The class name is MongoDB in a file called mongodb.php under application/libraries folder.

Inside constructor of the library class we are establish database connection.

We first get the Codeigniter instance into ci variable.

Next we load our mongodb.php config file. Then we retrieve different config items. If you want you can also auto-load this config file using autoload.php under application/config folder.

Finally we check whether authentication is required or not and we establish database connection.

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

/**
* Author: https://www.roytuts.com
*/

class MongoDB {
	
	private $conn;
	
	function __construct() {
		$this->ci =& get_instance();
		$this->ci->load->config('mongodb');
		
		$host = $this->ci->config->item('host');
		$port = $this->ci->config->item('port');
		$username = $this->ci->config->item('username');
		$password = $this->ci->config->item('password');
		$authenticate = $this->ci->config->item('authenticate');
		
		try {
			if($authenticate === TRUE) {
				$this->ci->conn = new MongoDB\Driver\Manager('mongodb://' . $username . ':' . $password . '@' . $host. ':' . $port);
			} else {
				$this->ci->conn = new MongoDB\Driver\Manager('mongodb://' . $host. ':' . $port);
			}
		} catch(MongoDB\Driver\Exception\MongoConnectionException $ex) {
			show_error('Couldn\'t connect to mongodb: ' . $ex->getMessage(), 500);
		}
	}
	
	function getConn() {
		return $this->ci->conn;
	}
	
}

Creating Model Class

Codeigniter model class is required to perform database operations and here we are going to create a class UserModel in a file called usermodel.php under application/models folder.

See we did not specify the database name during connection to MongoDB server in library but here in the model class we are going to specify it.

We are also specifying the collection name where we want to store our documents or entries.

We load the mongodb library inside the constructor and get the connection object.

Each document has unique _id generated by MongoDB and it is a BSON object. Therefore whenever you want to search record based on _id value you must wrap in a BSON object otherwise you won’t be able to find the document.

Here we have defined functions for CRUD operations and it is understandable from the source code.

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

/**
* Author: https://www.roytuts.com
*/

class UserModel extends CI_model {
	
	private $database = 'roytuts';
	private $collection = 'user';
	private $conn;
	
	function __construct() {
		parent::__construct();
		$this->load->library('mongodb');
		$this->conn = $this->mongodb->getConn();
	}
	
	function get_user_list() {
		try {
			$filter = [];
			$query = new MongoDB\Driver\Query($filter);
			
			$result = $this->conn->executeQuery($this->database.'.'.$this->collection, $query);

			return $result;
		} catch(MongoDB\Driver\Exception\RuntimeException $ex) {
			show_error('Error while fetching users: ' . $ex->getMessage(), 500);
		}
	}
	
	function get_user($_id) {
		try {
			$filter = ['_id' => new MongoDB\BSON\ObjectId($_id)];
			$query = new MongoDB\Driver\Query($filter);
			
			$result = $this->conn->executeQuery($this->database.'.'.$this->collection, $query);
			
			foreach($result as $user) {
				return $user;
			}
			
			return NULL;
		} catch(MongoDB\Driver\Exception\RuntimeException $ex) {
			show_error('Error while fetching user: ' . $ex->getMessage(), 500);
		}
	}
	
	function create_user($name, $email) {
		try {
			$user = array(
				'name' => $name,
				'email' => $email
			);
			
			$query = new MongoDB\Driver\BulkWrite();
			$query->insert($user);
			
			$result = $this->conn->executeBulkWrite($this->database.'.'.$this->collection, $query);
			
			if($result == 1) {
				return TRUE;
			}
			
			return FALSE;
		} catch(MongoDB\Driver\Exception\RuntimeException $ex) {
			show_error('Error while saving users: ' . $ex->getMessage(), 500);
		}
	}
	
	function update_user($_id, $name, $email) {
		try {
			$query = new MongoDB\Driver\BulkWrite();
			$query->update(['_id' => new MongoDB\BSON\ObjectId($_id)], ['$set' => array('name' => $name, 'email' => $email)]);
			
			$result = $this->conn->executeBulkWrite($this->database.'.'.$this->collection, $query);
			
			if($result == 1) {
				return TRUE;
			}
			
			return FALSE;
		} catch(MongoDB\Driver\Exception\RuntimeException $ex) {
			show_error('Error while updating users: ' . $ex->getMessage(), 500);
		}
	}
	
	function delete_user($_id) {
		try {
			$query = new MongoDB\Driver\BulkWrite();
			$query->delete(['_id' => new MongoDB\BSON\ObjectId($_id)]);
			
			$result = $this->conn->executeBulkWrite($this->database.'.'.$this->collection, $query);
			
			if($result == 1) {
				return TRUE;
			}
			
			return FALSE;
		} catch(MongoDB\Driver\Exception\RuntimeException $ex) {
			show_error('Error while deleting users: ' . $ex->getMessage(), 500);
		}
	}
	
}

Creating Controller Class

Create a controller file usercontroller.php under application/controllers with the following source code.

The below controller class handles request and response for clients.

We define here methods for performing CRUD operations.

The controller class has one method called index() that loads all users from the model class and sends to the view file.

We perform validations on input fields while creating new user or update existing user.

We use Codeigniter’s built-in method valid_email to validate the email address.

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

/**
* Author: https://www.roytuts.com
*/

class UserController extends CI_Controller {
	 
	function __construct() {
		parent::__construct();
		$this->load->model('usermodel');
	}
	 
	function index() {
		$data['users'] = $this->usermodel->get_user_list();
		$this->load->view('users', $data);
	}
	
	public function create() {
        if ($this->input->post('submit')) {
            $this->form_validation->set_rules('name', 'Full Name', 'trim|required');
            $this->form_validation->set_rules('email', 'Email Address', 'trim|valid_email|required');

            if ($this->form_validation->run() !== FALSE) {
                $result = $this->usermodel->create_user($this->input->post('name'), $this->input->post('email'));
				if($result === TRUE) {
					redirect('/');
				} else {
					$data['error'] = 'Error occurred during saving data';
					$this->load->view('user_create', $data);
				}
            } else {
				$data['error'] = 'Error occurred during saving data: all fields are required';
                $this->load->view('user_create', $data);
            }
        } else {
            $this->load->view('user_create');
        }
    }
	
	function update($_id) {
		if ($this->input->post('submit')) {
            $this->form_validation->set_rules('name', 'Full Name', 'trim|required');
            $this->form_validation->set_rules('email', 'Email Address', 'trim|valid_email|required');

            if ($this->form_validation->run() !== FALSE) {
                $result = $this->usermodel->update_user($_id, $this->input->post('name'), $this->input->post('email'));
                if($result === TRUE) {
					redirect('/');
				} else {
					$data['error'] = 'Error occurred during updating data';
					$this->load->view('user_update', $data);
				}
            } else {
				$data['error'] = 'error occurred during saving data: all fields are mandatory';
                $this->load->view('user_update', $data);
            }
        } else {
			$data['user'] = $this->usermodel->get_user($_id);
            $this->load->view('user_update', $data);
        }
	}
	
	function delete($_id) {
		if ($_id) {
            $this->usermodel->delete_user($_id);
        }
		redirect('/');
	}
	
}

Creating View Files

We will create few view files to perform our CRUD operations.

Display Users

To display all users on the view create a file called users.php under application/views folder.

<?php
	defined('BASEPATH') OR exit('No direct script access allowed');
?>

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="utf-8">
	<title>Codeigniter MongoDB Create Read Update Delete Example</title>
	<link rel="stylesheet" type="text/css" href="<?=base_url()?>assets/css/style.css"/>
</head>
<body>

<div>
	<h1>Codeigniter MongoDB Create Read Update Delete Example</h1>
	
	<div>
		<?php echo anchor('/usercontroller/create', 'Create User');?>
	</div>

	<div id="body">
		<?php
			if ($users) {
		?>
        <table class="datatable">
            <thead>
				<tr>
					<th>Name</th>
					<th>Email</th>
					<th>Acions</th>
                </tr>
            </thead>
			<tbody>
				<?php
					$i = 0;
					foreach ($users as $user) {
						$col_class = ($i % 2 == 0 ? 'odd_col' : 'even_col');
						$i++;
					?>
					<tr class="<?php echo $col_class; ?>">
						<td>
							<?php echo $user->name; ?>
						</td>
						<td>
							<?php echo $user->email; ?>
						</td>
						<td>
							<?php echo anchor('/usercontroller/update/' . $user->_id, 'Update'); ?>
							  
							<?php echo anchor('/usercontroller/delete/' . $user->_id, 'Delete', array('onclick' => "return confirm('Do you want delete this record')")); ?>
						</td>
					</tr>
					<?php
				}
				?>
			</tbody>
        </table>
    <?php
        } else {
            echo '<div style="color:red;"><p>No Record Found!</p></div>';
        }
    ?>
	</div>
</div>

</body>
</html>
Applying Style

As you see we have added one style.css file which should be kept under assets/css folder under the project root directory.

table.datatable {
	width:100%;
	border: none;
	background:#fff;
}
table.datatable td.table_foot {
	border: none;
	background: #fff;
	text-align: center;
}
table.datatable tr.odd_col {
	background: none;
}
table.datatable tr.even_col {
	background: #ddd;
}
table.datatable td {
	font-size:10pt;
	padding:5px 10px;
	border-bottom:1px solid #ddd;
	text-align: left;
}
table.datatable th {
	text-align: left;
	font-size: 8pt;
	padding: 10px 10px 7px;   
	text-transform: uppercase;
	color: #fff;
	background:url('../img/table/head.gif') left -5px repeat-x;
	font-family: sans-serif;
}

In the above style we also used one image which you will find when you download the source code at the end of the tutorial.

Creating User

We need a file user_create.php under application/views folder with below source code to create a new user.

<?php
	defined('BASEPATH') OR exit('No direct script access allowed');
?>
<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <title>Codeigniter MongoDB Create Read Update Delete Example</title>
    </head>
    <body>
        <div id="container">
            <h1>Codeigniter MongoDB Create Read Update Delete Example</h1>
			
			<div>
				<?php echo anchor('/usercontroller', 'Back to Users');?>
			</div>
			
            <div id="body">
                <?php
					if (isset($error)) {
						echo '<p style="color:red;">' . $error . '</p>';
					} else {
						echo validation_errors();
					}
                ?>

                <?php 
					$attributes = array('name' => 'form', 'id' => 'form');
					echo form_open($this->uri->uri_string(), $attributes);
                ?>

                <h5>Full Name</h5>
                <input type="text" name="name" value="<?php echo set_value('name');?>" size="50" />

                <h5>Email Address</h5>
                <input type="text" name="email" value="<?php echo set_value('email');?>" size="50" />

                <p><input type="submit" name="submit" value="Submit"/></p>
                
                <?php echo form_close(); ?>
            </div>
        </div>
    </body>
</html>

Updating User

We may need to update existing user. So we create a file user_update.php under application/views folder.

<?php
	defined('BASEPATH') OR exit('No direct script access allowed');
?>
<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <title>Codeigniter MongoDB Create Read Update Delete Example</title>
    </head>
    <body>
        <div id="container">
            <h1>Codeigniter MongoDB Create Read Update Delete Example</h1>
			
			<div>
				<?php echo anchor('/usercontroller', 'Back to Users');?>
			</div>
			
            <div id="body">
                <?php
					if (isset($error)) {
						echo '<p style="color:red;">' . $error . '</p>';
					} else {
						echo validation_errors();
					}
                ?>

                <?php 
					$attributes = array('name' => 'form', 'id' => 'form');
					echo form_open($this->uri->uri_string(), $attributes);
                ?>

                <h5>Full Name</h5>
                <input type="text" name="name" value="<?php echo isset($user)?$user->name:set_value('name'); ?>" size="50" />

                <h5>Email Address</h5>
                <input type="text" name="email" value="<?php echo isset($user)?$user->email:set_value('email'); ?>" size="50" />

                <p><input type="submit" name="submit" value="Submit"/></p>
                
                <?php echo form_close(); ?>
            </div>
        </div>
    </body>
</html>

We are not going to show user details in separate page because we can see all information for user on the home page.

We don’t also need a separate page for deleting user because we will just perform an action to delete a user from the home page.

Testing the Application

Make sure your Apache 2.4 and MongoDB 4.0.10 are running.

Initially when you hit the URL http://[::1]/codeIgniter-3.1.10-mongodb/index.php/, you won’t have any user because we didn’t create any user till now.

Creating User

Create a new user using below information:

codeigniter mongodb crud example

If successfully created then you will be redirected to the home page with list of users.

Display Users – Home Page

We have created just one user, so it is displaying only one user.

codeigniter mongodb crud example

Updating User

If you click on Update link to update the user and change the input value.

codeigniter mongodb crud example

Once you update by clicking on Submit button you will be redirected to the home page with updated value.

Deleting User

If you delete a user by clicking on Delete link then you will get a confirmation alert box. If you click on Yes, the record will be deleted.

codeigniter mongodb crud example

That’s all. Hope you got idea on Codeigniter MongoDB CRUD example.

Source Code

Thanks for reading.

Leave a Reply

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