CRUD Operations Using PHP and MongoDB

This Tutorial helps to Create CRUD(Create, Read, Update and Delete) Operations using Mongo database and PHP. I have already shared a tutorial to Create Bootstrap Table Listing Using Mongo. I am using php7 with mongodb.

I am extending the above tutorial and adding add, edit and delete functionality. I will restructure the code for this tutorial. The Mongo connection object will go into a separate file. I am assuming you have installed MongoDB into your machine, if not Please read this tuorial.

We also need mongo libs driver for php, which helps to PHP for creating a connection with mongo and its operation.

PHP CRUD Operation Using PHP

Let us start how to perform CRUD (Create/Read/Update/Delete) operations in MongoDB. We will create the following files into this project.

  • index.php: This file will responsible for the main application entry file and listing of data.
  • connection.php: This file will have mongo DB connection information.
  • add.php: This is a view file for add a record.
  • edit.php: This is a view file for edit a record.

How to Create Connection Mongo DB with PHP

We will create connection.php file and added the below code into this file.

<?php
// Config
$dbhost = 'localhost';
$dbname = 'Employee_db';

// Connect to test database
$m = new Mongo("mongodb://$dbhost");

$db = $m->$dbname;
// select the collection
$collection = $db-&gt;movie;
?>

We have passed dbname and mongo server hostname.

HTML Table Listing with Actions Button

I will modify index.php and added an action button for add/edit and delete record.

we will include connection.php file into the top of index.php file –

<?php
include_once('connection.php');
// pull a cursor query
$cursor = $collection->find();
?>

We have also fetched all data from the mongo database using cursor query and will use into table to display.

Let’s Create HTML action buttons into index.php file to add, edit and delete record –

<div class="clearfix well"><a class="btn btn-primary pull-right" href="add.php">Add New</a></div>
<div class="col-xs-6">

<?php }
		?>
<table id="simple-table" class="table table-striped table-bordered table-hover">
<thead>
<tr>
<th>Name</th>
<th>Age</th>
<th>Roll Number</th>
<th>Action</th>
</tr>
</thead>
<tbody><?php 
		foreach ($cursor as $document) {?>
<tr>
<td><?php echo $document['name']?></td>
<td><?php echo $document['age']?></td>
<td><?php echo $document['rno']?></td>
<td>
<!-- edit this nerd (uses the edit method found at GET /nerds/{id}/edit --> 
<a class="btn btn-small btn-info" href="edit.php?id=<?php echo $document['_id']?>">Edit</a>
<form class="inline" action="index.php?_id=<?php echo $document['_id']; ?>" method="post"><input name="_method" type="hidden" value="DELETE"> <button id="delete-rec" class="btn btn-danger" name="delete-rec" type="submit">Delete</button></form></td>
</tr>
</tbody>
</table>
</div>

How To Add Record Using MongoDB and PHP

We will add a new record using php. The record will insert into mongo database. Let’s create add.php file –

<div class="page-content">

<div class="col-xs-6"><?php if(isset($message) && $message['message'] != '' && $message['status'] == 'error') { ?>


<div class="alert alert-danger">

<h3><?php echo $message['message']; ?></h3>


<?php echo $msg = implode("</br---->", $message['errors']); ?>
</div>


<?php } ?> <?php if(isset($message) && isset($message['status']) && $message['status'] == 'success') { ?>

<div class="alert alert-success"><?php echo $message['message']; ?></div>


<?php } ?>

<div class="col-xs-12">

<h3 class="header smaller lighter blue">Add Employee</h3>


<!-- will be used to show any messages -->
<form accept-charset="UTF-8" action="" method="post">

<div class="col-md-12">

<div class="form-area">

<div class="alert alert-success hide"></div>


<div class="alert alert-danger hide"></div>


<div class="form-group"><input id="name" class="form-control" name="name" type="text" value="<?php echo isset($_POST['name']) ? $_POST['name'] : ''; ?>" placeholder="Name"></div>


<div class="form-group"><input id="age" class="form-control" name="age" pattern="[0-9]*" type="number" value="<?php echo isset($_POST['age']) ? $_POST['age'] : ''; ?>" placeholder="Age"></div>


<div class="form-group"><input id="rno" class="form-control" name="rno" type="number" value="<?php echo isset($_POST['rno']) ? $_POST['rno'] : ''; ?>" placeholder="Roll number"></div>


<button id="add-student" class="btn btn-primary pull-right" name="add-student" type="submit">Add Student</button>
</div>

</div>

</form>
</div>

</div>

</div>

In the above code, first we will display errors and success message. We have added add a record HTML view using bootstrap css classes.

The Above HTML form will post data to the server using the HTTP Post method, We will get posted data into the same add.php page. The following code will add into the top of the add.php file.

<?php
include_once('connection.php');
$message = array('status'=----> 'error', 'errors'=&gt; [], 'message' =&gt; '');
$validate = false;
$post_data = array();
if(isset($_POST['add-student'])){ //check if form was submitted
	
	if(!empty($_POST['name'])) {
		$post_data['name'] = $_POST['name'];
	} else {
		$message['errors'][] = "Name is Empty";
		$validate = true;
	}
	if(!empty($_POST['age'])) {
		$post_data['age'] = $_POST['age'];
	} else {
		$message['errors'][] = "Age is Empty";
		$validate = true;
	}
	if(!empty($_POST['rno'])) {
		$post_data['rno'] = $_POST['rno'];
	} else {
		$message['errors'][] = "Roll Number is Empty";
		$validate = true;
	}
	
	if(!$validate) {
		$collection-&gt;insert($post_data);
		$message['message'] = 'SuccessFully! Created Record.';
		$message['status'] = 'success';
		$_POST = array();
	} else {
		$message['message'] = 'Validation Failed!';
	}
  //$input = 
  //print_R($message['errors']);die;; //get input text
  //$message = "Success! You entered: ".$input;
}    
?>

The first line will have the mongo DB connection object and then the check method is POST or GET, if the method is GET then we will simply show the add a record view, When the form post the data then Method would be POST and validate posted data.

We are displaying a message if the validation has failed, Otherwise inserting a new record into the mongo database. The mongo insert() method helps to add a new record into MongoDB collection.

How To Edit A Record Using MongoDb and PHP

Let’s edit an existing record using PHP in the Mongo database. Created a edit.php file and added below HTML code. This will display the edit form to the end user to enable edit record functionality.

<div class="page-content">
<div class="col-xs-6"><?php if(isset($message) && $message['message'] != '' && $message['status'] == 'error') { ?>
<div class="alert alert-danger">
<h3><?php echo $message['message']; ?></h3>
<?php echo $msg = implode("</br>", $message['errors']); ?>

</div>
<?php } ?> <?php if(isset($message) && isset($message['status']) && $message['status'] == 'success') { ?>
<div class="alert alert-success"><?php echo $message['message']; ?></div>
<?php } ?>
<div class="col-xs-12">
<h3 class="header smaller lighter blue">Edit Employee</h3>
<!-- will be used to show any messages -->

<form accept-charset="UTF-8" action="" method="post">
<div class="col-md-12">
<div class="form-area">
<div class="alert alert-success hide"></div>
<div class="alert alert-danger hide"></div>
<div class="form-group"><input name="_id" type="hidden" value="<?php echo $post_data['_id'];?>"> <input id="name" class="form-control" name="name" type="text" value="<?php echo $post_data['name']; ?>" placeholder="Name"></div>
<div class="form-group"><input id="age" class="form-control" name="age" pattern="[0-9]*" type="number" value="<?php echo $post_data['age']; ?>" placeholder="Age"></div>
<div class="form-group"><input id="rno" class="form-control" name="rno" type="number" value="<?php echo $post_data['rno']; ?>" placeholder="Roll number"></div>
<button id="edit-student" class="btn btn-primary pull-right" name="edit-student" type="submit">Update Student</button>

</div>
</div>
</form></div>
</div>
</div>

We have added a div to display error and success message notifications. The next div have contained an edit form, we are using the bootstrap css framework to display the view file. We are using an HTTP POST method to post form data to the server.

The following code will add to top of the edit.php file.

<?php
include_once('connection.php');

if(isset($_POST['edit-student'])){ //check if form was submitted
	$message = array('status'=----> 'error', 'errors'=> [], 'message' => '');

	$validate = false;
	if(!empty($_POST['name'])) {
		$post_data['name'] = $_POST['name'];
	} else {
		$message['errors'][] = "Name is Empty";
		$validate = true;
	}
	if(!empty($_POST['age'])) {
		$post_data['age'] = $_POST['age'];
	} else {
		$message['errors'][] = "Age is Empty";
		$validate = true;
	}
	if(!empty($_POST['rno'])) {
		$post_data['rno'] = $_POST['rno'];
	} else {
		$message['errors'][] = "Roll Number is Empty";
		$validate = true;
	}
	
	if(!$validate) {
		$collection->update(array('_id' => new MongoId($_POST['_id'])), array('$set' => $post_data));
		//$collection->insert($post_data);
		$message['message'] = 'SuccessFully! Updated Record.';
		$message['status'] = 'success';
		$post_data = $collection->findOne(array('_id' => new MongoId($_GET['id'])));
	} else {
		$message['message'] = 'Validation Failed!';
	}
  //$input = 
  //print_R($message['errors']);die;; //get input text
  //$message = "Success! You entered: ".$input;
} else {
	if(!empty($_GET['id'])) {
		$post_data = $collection->findOne(array('_id' => new MongoId($_GET['id'])));
	}
} 
?>

First, We have added the mongo connection file into here to access mongo object.

The HTTP method help to identify whether the form data has been post or not – If the form data is not posted then we will show the edit form layout, if the form data is posted then we will process data validation. After successfully validating data, we are updating data into the mongo db.

We are displaying a message if the validation has failed. We are inserting a new record into the mongo database when the validation passed. The mongo update() method helps to update existing records into the mongodb.

How To Delete Record into MongoDb Using PHP

I have already added the delete action button, Now we will add functionality to delete records from mongo database. Let’s add the below code into the top of the index.php file –

if ($_SERVER['REQUEST_METHOD'] === "POST" && isset($_POST['_method'])) {
     // The delete record
	if(isset($_GET['_id']))
	$collection->remove(array( '_id' => new MongoInt32($_GET['_id'])));
}

Conclusion:

Created MongoDB connection with PHP. We have also created Add, Edit and Delete CRUD operation using MongoDB and PHP. The mongo libs have many inbuilt methods to support daily uses MongoDB operation.

Leave a Reply

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