How to connect MongoDB using PHP

After posting content about MongoDB, just thinking of posting another content about MongoDB but with PHP. Yes this post about connecting MongoDB with PHP,  if your are using Windows OS you can check with below link about MongoDB installations & enable extension in Wamp Server.

Before starting up our tutorial let’s check MongoDB is running status by executing simple script to check in PHP.

MongoClient is used to create and manage the connections between PHP and MongoDB.

<?php
$con = new MongoClient( "mongodb://127.0.0.1:27017" );

Let’s  create simple  feedback form to add and show the data from MongoDB. first create demo database.  You no need to create collection because when you do the first insert collection will automatically created and insert the data into it.

Index.html

<html>
<head>
<title>Feedback Form using MongoDB with PHP</title>
</head>
<body>
<form action="post.php" method="post" id="feedbackForm" name="feedbackForm">
	<div>
	<div style="float:left;width:100px;">
	<table cellpadding="4" cellspacing="4">
	
	<tr>
	<td>Name</td>
	<td><input type="text" name="txtName" id="txtName" size="40"></td>
	</tr>
	<tr>
	<td>Email</td>
	<td><input type="text" name="txtEmail" id="txtEmail" size="40"></td>
	</tr>
	<tr>
	<td valign="top">Feedback</td>
	<td><textarea name="txtFeedback" id="txtFeedback" cols="50" rows="10"></textarea></td>
	</tr>
	<tr>
	<td valign="top"></td>
	<td><input class="submit" type="submit" value="Submit"></td>
	</tr>
	
	</table>
	</div>
	<div id='divLoad' style="float:right;width:641px;height:50px;height:500px;overflow-y:scroll;display:none;">
	<select id="selOrderBy" onchange="return loadData(this.value);">		
		<option value="1">Order By Date Asc</option>
		<option value="-1">Order By Date Desc</option>
	</select>
	<br /><br />
	<div id="divData" width="100px"></div>
	</div>
	</div>
	</form>
	<script src="//code.jquery.com/jquery-1.9.1.js"></script>
	<script src="//ajax.aspnetcdn.com/ajax/jquery.validate/1.9/jquery.validate.min.js"></script>	
	
	<script src="js/form-validation.js"></script>
	<script src="js/show-data.js"></script>
</body>
</html>

In our Html we have included JS files  jquery-1.9.1.js and jquery.validate.min.js for ajax and validation purpose. form-validation.js and show-data.js used for validate the feedback form and show the data from MongoDB.

form-validation.js

$(function() {
	$("#feedbackForm").validate({
		rules: {
			txtName: "required",
			txtEmail: {
				required: true,
				email: true
			},
			txtFeedback: "required"
		},
		messages: {
			txtName: "<br />Please enter your Name",
			txtEmail: "<br />Please enter a valid Email Address",
			txtFeedback: "<br />Please enter feedback"
		},
		submitHandler: function(form) {
			form.submit();
		}
	});		
});

show-data.js

loadData(1);
function loadData(id) {
	$.getJSON( "ajax.call.php?d="+id, function( data ) {
		$s = '<table width="100%">'; 
		if(data.length>0)
		{
			$("#divLoad").show();
		}			
		for(i in data)
		{
			$s += '<tr>';
			$s += '<td>';
			$s += '<table width="100%">';
			$s += '<tr>';
			$s += '<td>'+data[i]._id.$id+'</td>';
			$s += '</tr>';
			$s += '<tr>';
			$s += '<td>Name : '+data[i].name+'</td>';
			$s += '</tr>';
			$s += '<tr>';
			$s += '<td>Email : '+data[i].email+'</td>';
			$s += '</tr>';
			$s += '<tr>';
			$s += '<td>Feedback : '+data[i].message+'</td>';
			$s += '</tr>';
			$s += '<tr>';
			$s += '<td>Date Time : '+data[i].date_time+'</td>';
			$s += '</tr>';
			$s += '<tr>';
			$s += '<td><hr /></td>';
			$s += '</tr>';
			$s += '</table>';
			$s += '</td>';
			$s += '</tr>';
		}
		$s += '<table>';
		$( "#divData" ).html( $s );
});
}

Config file which will connect MongoDB and PHP.

config.php

<?php
$con = new MongoClient( "mongodb://127.0.0.1:27017" );
$db = $con->demo;
$collection = $db->feedback;

post.php file store the data into feedback collections

<?php require_once("config.php");

if(!empty($_POST["txtName"]) && !empty($_POST["txtEmail"]) && !empty($_POST["txtEmail"])) {

$name = $_POST["txtName"];
$email = $_POST["txtEmail"];
$message = addslashes($_POST["txtFeedback"]);


$addData = array('name' =>$name,'email'=>$email,'message'=>$message,'date_time'=>date("Y-m-d H:i:s"));
$collection->insert($addData);	
}

header("Location: index.html?.".strtotime("now"));

ajax.call.php script executed whenever page is reload, there is option to sort the data order by date asc and desc.

<?php require_once("config.php");

$idValue = (isset($_GET["d"])) ? $_GET["d"] : 1;
$cursor = $collection->find(array())->sort(array("date_time"=>(int)$idValue));

$arr = []; 
foreach ($cursor as $document) {
    $arr[] = $document;
}

echo json_encode($arr);

 

 

  • Nice article, MongoDB seems like a new trend with PHP. Good choice of topic.

    • Thanks for your valuable feedback, more MongoDB post coming.
      please subscribe our website for regular updates.