Home > Backend Development > PHP Tutorial > Building a Simple Blog App with MongoDB and PHP

Building a Simple Blog App with MongoDB and PHP

Joseph Gordon-Levitt
Release: 2025-02-22 10:21:16
Original
916 people have browsed it

Building a Simple Blog App with MongoDB and PHP

Key Takeaways

  • MongoDB is a document-oriented NoSQL database that enhances performance and scalability, making it ideal for blog applications where collections and documents can be easily managed.
  • The PHP MongoDB driver is essential for connecting PHP applications to MongoDB, allowing for CRUD operations directly from PHP scripts.
  • Simple user authentication can be implemented using HTTP auth for the admin sections of the blog, though for more robust applications, a comprehensive authentication framework is recommended.
  • The blog application utilizes basic CRUD operations for managing blog posts, with additional functionality for comments, all stored within MongoDB collections.
  • The application structure includes separate directories and files for administrative tasks and views, promoting a simplistic form of MVC architecture which can be further developed using full-scale frameworks.

Introduction

If you want to create a blog using MongoDB and PHP, this article will teach you to:

  • Connect to a MongoDB database
  • Save documents in a collection
  • Query documents in a collection
  • Perform range queries
  • Sort documents, update a document, delete one or more documents from a collection

The reason I chose to build a blog application is because it is a basic CRUD application and it is very suitable for easing into PHP and MongoDB web development. We will build a plain user interface using Bootstrap with simple textboxes and buttons. A MongoDB database will store all the content. You can download full source from github, see a demo frontend here and try the demo app’s backend with the user name and password being duythien.

What is MongoDB

According to the official website MongoDB is a document database that provides high performance, high availability, and easy scalability. MongoDB falls into the group of documents-oriented NoSQL databases. For other subtypes of NoSQL databases, see here.

MongoDB Concepts: Databases, Collections, and Documents

  1. Database: MongoDB groups data into databases in the very same way as most relational databases do. If you have any experience with relational databases, you should think of these the same way. In an RDBMS, a database is a set of tables, stored procedures, views, and so on. In MongoDB, a database is a set of collections. A MongoDB database contains one or more collections. For example, a database for a blogging application named blog may typically have the collections articles, authors, comments, categories, and so on.

  2. Collection: A collection is the equivalent of an RDBMS table. A collection exists within a single database. Collections do not enforce a schema. Documents within a collection can have different fields. Typically, all documents in a collection have a similar or related purpose.

  3. Documents: A record in a MongoDB collection and the basic unit of data in MongoDB. Documents are analogous to JSON objects but exist in the database in a more type-rich format known as BSON. A document contains a set of fields or key-value pairs. The best way to think of a document is as a multidimensional array. In an array, you have a set of keys that map to values (Document == Array). See Documents.

Installing MongoDB

MongoDB runs on most platforms and supports 32-bit and 64-bit architectures. MongoDB is available as a binary, or as a package. In production environments, use 64-bit MongoDB binaries. This section will cover installation on Ubuntu Linux and Windows. For other operating systems, please see their documentation.

This is how Mongo is installed on Ubuntu Linux. Open terminal and execute the following:

sudo apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv 7F0CEB10
#
echo 'deb http://downloads-distro.mongodb.org/repo/ubuntu-upstart dist 10gen' | sudo tee /etc/apt/sources.list.d/mongodb.list
Copy after login
Copy after login
Copy after login
Copy after login

Now issue the following command to update your repository and install the latest stable version of MongoDB:

sudo apt-get update
sudo apt-get install mongodb-10gen
Copy after login
Copy after login
Copy after login

Done, you have successfully installed MongoDB. Now start and stop service MongoDB via command line below.

sudo service mongodb start
sudo service mongodb stop
Copy after login
Copy after login
Copy after login

In case of start error to try run the following command:

sudo mongod --fork --logpath /var/log/mongodb/mongodb.log
#or
sudo mongod -f /etc/mongodb.conf
Copy after login
Copy after login
Copy after login

The following describes how to install it on Windows:

Head on over to the downloads page on the MongoDB official website. Click on the download link for the latest stable release under Windows.

After the download is finished, extract and move it into C: . MongoDB requires a data folder in which to store its files. The default location for the MongoDB data directory is C:datadb. If it doesn’t exist, create it.

To start MongoDB, execute from the Command Prompt

C:\> cd \mongodb\bin
C:\mongodb\bin> mongod
Copy after login
Copy after login
Copy after login

Done, you have successfully installed MongoDB. Now start and stop service MongoDB via command line below.

net start MongoDB
net stop  MongoDB
Copy after login
Copy after login
Copy after login

Installing the PHP driver for MongoDB

The MongoDB server is built to already work with your current web server, but not PHP. To make PHP talk to the MongoDB server, we are going to need the PHP-MongoDB driver. It is a PHP extension library.

If you use Linux install it easily via:

sudo pecl install mongo
Copy after login
Copy after login
Copy after login

Add the line extension=mongo.so to your php.ini configuration and you’re good to go:

sudo -i
echo 'extension=mongo.so' >> /etc/php5/apache2/php.ini
Copy after login
Copy after login

Restart your web server and verify via command line:

php -i |grep "mongo"
php --re mongo
Copy after login
Copy after login

Installing the Driver on Windows

Let us try installing the driver on a Windows machine running PHP 5.4 on Apache (XAMPP):

  1. Download the ZIP archive https://github.com/mongodb/mongo-php-driver/downloads on your machine and extract it.
  2. Copy the php_mongo.dll file from the extracted folder to the PHP extension directory(C:xamppphpext).
  3. Open the php.ini file inside your PHP installation and add the following line: extension=php_mongo.dll
  4. Save the file and close it. Restart the XAMP.
  5. Open up your text editor and add the following code to a new file:, save the file as phpinfo.php inside the DocumentRoot of the Apache web server (htdocs) and open the PHP script in the browser. If you see mongo in the PHP info, the installation was successful.

Mongo Web Development with PHP

Connecting to a MongoDB Database Server

Connecting to MongoDB from PHP is very similar to connecting to any other database. The default host is localhost, and the default port is 27017.

sudo apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv 7F0CEB10
#
echo 'deb http://downloads-distro.mongodb.org/repo/ubuntu-upstart dist 10gen' | sudo tee /etc/apt/sources.list.d/mongodb.list
Copy after login
Copy after login
Copy after login
Copy after login

Connecting to a remote host with optional custom port and auth:

sudo apt-get update
sudo apt-get install mongodb-10gen
Copy after login
Copy after login
Copy after login

Selecting a Database

Once the database server connection is established, we will use it to access a database. The defined way to do this is:

sudo service mongodb start
sudo service mongodb stop
Copy after login
Copy after login
Copy after login

The Basics (CRUD Operations)

MongoDB provides rich semantics for reading and manipulating data. CRUD stands for create, read, update, and delete. These terms are the foundation for all interactions with the database.

Creating/Selecting a Collection

Selecting and creating a collection is very similar to accessing and creating a database. If a collection does not exist, it is created:

sudo mongod --fork --logpath /var/log/mongodb/mongodb.log
#or
sudo mongod -f /etc/mongodb.conf
Copy after login
Copy after login
Copy after login

For example, this creates the collection “posts” in my blog:

C:\> cd \mongodb\bin
C:\mongodb\bin> mongod
Copy after login
Copy after login
Copy after login

Creating a Document

Creating a document in MongoDB could not be easier. Create an array. Pass it into the insert method on the collection object

net start MongoDB
net stop  MongoDB
Copy after login
Copy after login
Copy after login

The insert() method stores the data in the collection. The $post array automatically receives a field named _id, which is the autogenerated unique ObjectId of the inserted BSON document. You could also use the save() method, which upserts – updates an existing record, or creates a new one if it doesn’t exist.

Reading a Document

To get data from a collection, I use the find() method, which gets all the data in a collection. findOne() returns only one document that satisfies the specified query criteria. The following examples will show you how to query one or more records.

sudo pecl install mongo
Copy after login
Copy after login
Copy after login

Updating a Document

Modifies an existing document or documents in a collection. By default, the update() method updates a single document. If the multi option is set to true, the method updates all documents that match the query criteria.

sudo apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv 7F0CEB10
#
echo 'deb http://downloads-distro.mongodb.org/repo/ubuntu-upstart dist 10gen' | sudo tee /etc/apt/sources.list.d/mongodb.list
Copy after login
Copy after login
Copy after login
Copy after login

The update() method takes two parameters. The first is criteria to describe the objects to update and the second the object with which to update the matching records. There is also a third optional parameter whereby you can pass in an array of options.

Mini blog

The structure of the project we’ll be building:

sudo apt-get update
sudo apt-get install mongodb-10gen
Copy after login
Copy after login
Copy after login

Before we start with our actual PHP code we need to create our files and folders like above.

config.php

This is your configuration file that tells our app how to connect to the database. This is where you have defined the database name, username and password of the user to access that database:

sudo service mongodb start
sudo service mongodb stop
Copy after login
Copy after login
Copy after login

where we define paramaters UserAuth and PasswordAuth to protect the admin folder via HTTP authentication. We’re using HTTP auth for simplicity here, seeing as the central theme of the article is connecting to MongoDB – you would usually use some sort of decent framework with ACL to build in access control.

app.php:

sudo mongod --fork --logpath /var/log/mongodb/mongodb.log
#or
sudo mongod -f /etc/mongodb.conf
Copy after login
Copy after login
Copy after login

admin

This is the folder that contains the CRUD code.

C:\> cd \mongodb\bin
C:\mongodb\bin> mongod
Copy after login
Copy after login
Copy after login

For the full file index.php see here. Above I used the view function in the class layout.php which will automatically load dashboard.view.php.

net start MongoDB
net stop  MongoDB
Copy after login
Copy after login
Copy after login

The GET parameter status corresponds to a CRUD action. For example, when status is “create”:

sudo pecl install mongo
Copy after login
Copy after login
Copy after login

Function view(‘admin/create’, $data) shows an HTML form where the user can write the title/content of a new blog post, or it saves the user-submitted data to MongoDB. By default the script displays the following HTML form:

sudo -i
echo 'extension=mongo.so' >> /etc/php5/apache2/php.ini
Copy after login
Copy after login

Building a Simple Blog App with MongoDB and PHP

Next let’s look at db.php, which can be found in full here

php -i |grep "mongo"
php --re mongo
Copy after login
Copy after login

The MongoDB cursor makes pagination easy. These cursor methods can be chained off of the cursor object that find returns and each other. Combining limit with skip makes pagination easy. These can also be combined with order. For example.

$connection = new Mongo();
Copy after login

index.php: template files can be found in the view folder; such as index.view.php. Here is an example of index.php:

$connecting_string =  sprintf('mongodb://%s:%d/%s', $hosts, $port,$database),
$connection=  new Mongo($connecting_string,array('username'=>$username,'password'=>$password));
Copy after login

Open your browser and navigate to http://duythien.dev/sitepoint/blog-mongodb. It lists all the current articles in the blog:

Building a Simple Blog App with MongoDB and PHP

single.php: When you view a single post page (click Read more on a post), you are looking at single.view.php in the views folder. Here is the logic of single.php:

$dbname = $connection->selectDB('dbname');
Copy after login

This file receives the _id of the article as an HTTP GET parameter. We invoke the findOne() method on the articles collection, sending the _id value as a parameter to the method. The findOne() method is used to retrieve a single document. See function getById() in file db.php

Building a Simple Blog App with MongoDB and PHP

Enter an arbitrary Name and Email in the input boxes under the comments section, put some text in the textarea as well. Then click on the Save button and the page will reload with the comment you just posted. This is what comment.php looks like:

sudo apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv 7F0CEB10
#
echo 'deb http://downloads-distro.mongodb.org/repo/ubuntu-upstart dist 10gen' | sudo tee /etc/apt/sources.list.d/mongodb.list
Copy after login
Copy after login
Copy after login
Copy after login

Comments for an article are stored in an array field of the document name comments. Each element of a comment is an embedded document that contains several fields.

Conclusion

In this article, we covered a basic CRUD introduction into PhP with MongoDB. We’ve even created a sort of very primitive MVC in the process (see full app on Github). It’s up to you to use a proper framework, implement authentication beyond the simple HTTP auth used here, and add more functionality, but the basics are in place and you can hack away at this demo application to your heart’s content.

For more information on MongoDB check out the online documentation. Did you enjoy this article? Let us know your thoughts!

Frequently Asked Questions (FAQs) about Building a Simple Blog App with MongoDB and PHP

What is MongoDB and why is it used in building a blog app?

MongoDB is a source-available cross-platform document-oriented database program. It is classified as a NoSQL database program because it uses JSON-like documents with optional schemas. MongoDB is used in building a blog app because of its high performance, high availability, and easy scalability. It works on the concept of collections and documents, making it easier to organize and manage data.

How does PHP integrate with MongoDB in creating a blog app?

PHP is a popular general-purpose scripting language that is especially suited to web development. It integrates with MongoDB through a PHP driver, which is a client-side library that provides a high-level API abstraction for some of the features of MongoDB. This allows PHP scripts to communicate with MongoDB servers and perform operations like querying and updating data.

What are the prerequisites for building a blog app with MongoDB and PHP?

To build a blog app with MongoDB and PHP, you need to have a basic understanding of PHP and MongoDB. You also need to have PHP and MongoDB installed on your system. Additionally, you need a text editor for writing your code and a web server for hosting your app.

How can I handle user authentication in my blog app?

User authentication in a blog app can be handled using sessions in PHP. When a user logs in, a session is started, and the user’s information is stored in session variables. These variables can be accessed throughout the user’s session, allowing you to restrict access to certain pages based on the user’s authentication status.

How can I implement CRUD operations in my blog app?

CRUD operations (Create, Read, Update, Delete) can be implemented in a blog app using PHP and MongoDB. PHP provides functions for interacting with MongoDB, allowing you to create documents (posts), read documents, update documents, and delete documents. The MongoDB PHP driver provides a simple API for these operations.

How can I handle errors in my blog app?

Error handling in a blog app can be done using PHP’s built-in error handling functions. These functions allow you to define custom error handling rules, create custom error handlers, and report errors. You can also log errors for debugging purposes.

How can I improve the performance of my blog app?

The performance of a blog app can be improved by optimizing your MongoDB queries, using indexes, and caching data. You can also improve performance by optimizing your PHP code, for example by using efficient loops and functions, and by minimizing the use of global variables.

How can I secure my blog app?

Security in a blog app can be achieved by implementing user authentication, sanitizing user input to prevent SQL injection attacks, and using secure connections (HTTPS). You should also keep your PHP and MongoDB installations up to date to benefit from the latest security patches.

How can I deploy my blog app?

A blog app can be deployed by uploading the PHP files and MongoDB database to a web server. You can use FTP or a version control system like Git for uploading files. You also need to configure your web server to handle PHP scripts and connect to your MongoDB database.

How can I add features like comments and likes to my blog app?

Features like comments and likes can be added to a blog app by creating additional collections in your MongoDB database for storing comments and likes. You can then use PHP to create, read, update, and delete comments and likes, and to associate them with specific posts.

The above is the detailed content of Building a Simple Blog App with MongoDB and PHP. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template