Wednesday, September 11, 2013

Simple CRUD with MongoDB and PHP

[caption id="attachment_904" align="alignnone" width="645"]MongoDB MongoDB[/caption]

Today we gonna make our hands dirty with some MongoDB stuff. MongoDB is a no-SQL type, schema-less database. Such databases can be very useful in situations where there is much more user-generated content. You should understand where you use MongoDB or Apache CouchDB rather than traditional relational databases. You may want to google for getting more details about MongoDB if you gonna try this tutorial as a newbie.

First download and install MongoDB in your environment.

As we are trying this tutorial in PHP, you should download mongo driver for PHP also.

Edit php.ini so that it can load mongo driver. Add this line(in Windows)
<pre>extension=php_mongo.dll</pre>

Now we are good to go.

Run MongoDB server and start Mongo shell.

First you need to create a database and add a database user. If this is the first time you 're going to create a database user, first you need to create an admin user. Read documentation for more details.

This tutorial is all about a simple CRUD application using MongoDB. In this application a blog post scenario is used for demonstrating CRUD operations. This scenario is very popular in MongoDB Hello World tutorials.

This tutorial does not include complete source code. You can download it here.

DB class

[sourcecode language="php"]
class DB {

const DBHOST = 'localhost';
const DBUSER = 'codezone4';
const DBPWD = '123';
const DBPORT = 27017;
const DBNAME = 'blog_db';

private static $instance;
public $connection;
public $databse;

private function __construct() {
$connection_string = sprintf('mongodb://%s:%s@%s:%d/%s', DB::DBUSER, DB::DBPWD, DB::DBHOST, DB::DBPORT, DB::DBNAME);
try {
$this->connection = new Mongo($connection_string);
$this->databse = $this->connection->selectDB(DB::DBNAME);
} catch (MongoConnectionException $e) {
throw $e;
}
}

static public function instantiate(){
if(!isset(self::$instance)){
$class = __CLASS__;
self::$instance = new $class;
}
return self::$instance;
}

public function get_collection($name){
return $this->databse->selectCollection($name);
}

}
[/sourcecode]

Add New Post

[sourcecode language="php"]
include 'db.class.php';
if(isset($_POST['add_post'])){
$title = $_POST['title'];
$content = $_POST['content'];

if(!empty($title) && !empty($content)){

$mongo =  DB::instantiate();
$post_collection = $mongo->get_collection('posts');
$post = array(
'_id' => hash('sha1', time() . $title),
'title' => $title,
'content' => $content,
'created_on' => new MongoDate()
);
$post_id = $post_collection->insert($post,array('safe'=>TRUE));
header('Location:../dashboard.php');
}
}
[/sourcecode]

No comments:

Post a Comment

How to enable CORS in Laravel 5

https://www.youtube.com/watch?v=PozYTvmgcVE 1. Add middleware php artisan make:middleware Cors return $next($request) ->header('Acces...