Creating a Simple Comment Section using PHP and SQLite Tutorial
In this tutorial, you will learn how to create a Simple Comment Section in your Web Application Projects using PHP and SQLite Database. Comment Section is one of the most common feature in a web application such as Blog Sites. This application feature allows users to leave a comment, ask questions, or feedback for a certain post/content. This kind of web application feature also allows other users to reply-to-comment which means other users can leave a comment under a specific comment too.
Here, I will be providing a very simple comment section web application in which app users can submit, read, reply, edit, and delete comments. The demo application that we will be creating don not require users to register and log in, this only requires entering the user name for each comment and reply.
Getting Started
In this tutorial source code, I used Bootstrap v5 for the design of application and XAMPP v3.3.0. Download and Install the said library and local web machine server to run the following script on your end. After Installing the XAMPP, open the XAMPP's php.ini file (i.e "C:\xampp\php\php.ini") in a text-editor and uncomment the ;extension=sqlite3. To do that, remove the (;) [semicolon]. Lastly, open your XAMPP's Control Panel and start the Apache
Creating the Database Connection
The follwing PHP scripts is the database connection script of our project. This also contains a script that creates the database and tables if not yet existed. Save this file as Connection.php
- <?php
- function my_udf_md5($string) {
- }
- Class DBConnection extends SQLite3{
- protected $db;
- function __construct(){
- $this->open(db_file);
- $this->createFunction('md5', 'my_udf_md5');
- `comment_id` INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,
- `sender` TEXT NOT NULL,
- `comment` TEXT NOT NULL,
- `date_created` TIMESTAMP DEFAULT (datetime('now','localtime'))
- )");
- `reply_id` INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,
- `comment_id` INTEGER NOT NULL,
- `sender` TEXT NOT NULL,
- `reply` TEXT NOT NULL,
- `date_created` TIMESTAMP DEFAULT (datetime('now','localtime')),
- FOREIGN KEY (`comment_id`) References `comments`(comment_id) ON DELETE CASCADE
- )");
- }
- function __destruct(){
- $this->close();
- }
- }
- $conn = new DBConnection();
Creating the Page Interfaces
The below source code files is a PHP files/scripts that contains the codes of each pages interfaces. In contains a combined HTML and PHP scripts. Save the following files according to the given filename above each file scripts.
This file contains the interface script of the application's Main Page. This contains also the query that list all the comments and replies submitted.
- <?php require_once('Connection.php') ?>
- <!DOCTYPE html>
- <html lang="en">
- <head>
- <meta charset="UTF-8">
- <meta http-equiv="X-UA-Compatible" content="IE=edge">
- <meta name="viewport" content="width=device-width, initial-scale=1.0">
- <title>Simple Comment Section</title>
- <link rel="stylesheet" href="./css/bootstrap.min.css">
- <script src="./js/jquery-3.6.0.min.js"></script>
- <script src="./js/bootstrap.min.js"></script>
- <style>
- :root {
- --bs-success-rgb: 71, 222, 152 !important;
- }
- html,
- body {
- height: 100%;
- width: 100%;
- font-family: Apple Chancery, cursive;
- }
- </style>
- </head>
- <body class="bg-light">
- <nav class="navbar navbar-expand-lg navbar-dark bg-primary bg-gradient" id="topNavBar">
- <div class="container">
- <a class="navbar-brand" href="https://sourcecodester.com">
- Sourcecodester
- </a>
- </div>
- </nav>
- <div class="container py-3" id="page-container">
- <h3>Simple Comment Section</h3>
- <div class="alert alert-<?php echo $_SESSION['response_type'] ?>">
- <p class="m-0"><?php echo $_SESSION['response_msg'] ?></p>
- </div>
- <?php
- endif;
- ?>
- <hr>
- <?php
- $comment_qry = $conn->query("SELECT * FROM `comments` order by strftime(date_created) asc ");
- while($row = $comment_qry->fetchArray()):
- ?>
- <div class="card mb-2">
- <div class="card-body">
- <div class="d-flex align-items-end">
- </div>
- <hr>
- <div class="lh-1">
- </div>
- <hr>
- <div class="w-100 d-flex justify-content-end">
- <a href="reply.php?comment_id=<?php echo $row['comment_id'] ?>" class="btn btn-primary btn-sm rounded-0 me-2">Reply</a>
- <a href="edit_comment.php?comment_id=<?php echo $row['comment_id'] ?>" class="btn btn-primary btn-sm rounded-0 me-2">Edit</a>
- <a href="delete_comment.php?comment_id=<?php echo $row['comment_id'] ?>" class="btn btn-danger btn-sm rounded-0">Delete</a>
- </div>
- </div>
- </div>
- <?php
- $reply_qry = $conn->query("SELECT * FROM `replies` where comment_id ='{$row['comment_id']}' order by strftime(date_created) asc ");
- while($rrow = $reply_qry->fetchArray()):
- ?>
- <div class="card mb-2" style="margin-left:15%">
- <div class="card-body">
- <div class="d-flex align-items-end">
- </div>
- <hr>
- <div class="lh-1">
- </div>
- <hr>
- <div class="w-100 d-flex justify-content-end">
- <a href="reply.php?reply_id=<?php echo $rrow['reply_id'] ?>&comment_id=<?php echo $row['comment_id'] ?>" class="btn btn-primary btn-sm rounded-0 me-2">Edit</a>
- <a href="delete_reply.php?reply_id=<?php echo $rrow['reply_id'] ?>" class="btn btn-danger btn-sm rounded-0">Delete</a>
- </div>
- </div>
- </div>
- <?php endwhile; ?>
- <?php endwhile; ?>
- <hr>
- <form id="comment-form" action="save_comment.php" method="POST">
- <div class="form-group">
- <label for="sender" class="control-label">Sender</label>
- <input type="text" name="sender" id="sender" class="form-control form-control-sm rounded-0" value="<?php echo isset($_SESSION['comment-post']) ? $_SESSION['comment-post']['sender'] : "" ?>" required/>
- </div>
- <div class="form-group">
- <label for="comment" class="control-label">Comment</label>
- <textarea name="comment" id="comment" cols="30" rows="2" class="form-control" style="resize:none" placeholder="Write your comment here" required><?php echo isset($_SESSION['comment-post']) ? $_SESSION['comment-post']['comment'] : "" ?></textarea>
- </div>
- <div class="form-group">
- <div class="col-12 mt-4">
- <div class="d-flex justify-content-end align-items-end">
- <button class="btn btn-sm btn-sm btn-primary rounded-0 me-2" type="submit">Save</button>
- <button class="btn btn-sm btn-sm btn-secondary rounded-0" type="reset">Cancel</button>
- </div>
- </div>
- </div>
- </form>
- </div>
- </body>
- </html>
This file contains the script for the page where the users can edit the comment.
- <?php require_once('Connection.php') ?>
- <?php
- echo "<script>alert('Comment ID is required.'); location.replace('./');</script>";
- exit;
- }
- ?>
- <!DOCTYPE html>
- <html lang="en">
- <head>
- <meta charset="UTF-8">
- <meta http-equiv="X-UA-Compatible" content="IE=edge">
- <meta name="viewport" content="width=device-width, initial-scale=1.0">
- <title>Simple Comment Section</title>
- <link rel="stylesheet" href="./css/bootstrap.min.css">
- <script src="./js/jquery-3.6.0.min.js"></script>
- <script src="./js/bootstrap.min.js"></script>
- <style>
- :root {
- --bs-success-rgb: 71, 222, 152 !important;
- }
- html,
- body {
- height: 100%;
- width: 100%;
- font-family: Apple Chancery, cursive;
- }
- </style>
- </head>
- <body class="bg-light">
- <nav class="navbar navbar-expand-lg navbar-dark bg-primary bg-gradient" id="topNavBar">
- <div class="container">
- <a class="navbar-brand" href="https://sourcecodester.com">
- Sourcecodester
- </a>
- </div>
- </nav>
- <div class="container py-3" id="page-container">
- <h3>Update Comment</h3>
- <div class="alert alert-<?php echo $_SESSION['response_type'] ?>">
- <p class="m-0"><?php echo $_SESSION['response_msg'] ?></p>
- </div>
- <?php
- endif;
- ?>
- <hr>
- <?php
- $comment_qry = $conn->query("SELECT * FROM `comments` where comment_id = '{$_GET['comment_id']}' ");
- $result = $comment_qry->fetchArray();
- if(!$result){
- echo "<script>alert('Unkown Comment ID.'); location.replace('./');</script>";
- exit;
- }else{
- ?>
- <form id="comment-form" action="save_comment.php" method="POST">
- <input type="hidden" name="comment_id" value="<?php echo $_GET['comment_id'] ?>" >
- <div class="form-group">
- <label for="sender" class="control-label">Sender</label>
- </div>
- <div class="form-group">
- <label for="comment" class="control-label">Comment</label>
- </div>
- <div class="form-group">
- <div class="col-12 mt-4">
- <div class="d-flex justify-content-end align-items-end">
- <button class="btn btn-sm btn-sm btn-primary rounded-0 me-2" type="submit">Save</button>
- <a class="btn btn-sm btn-sm btn-secondary rounded-0" href="./">Cancel</a>
- </div>
- </div>
- </div>
- </form>
- <?php } ?>
- <hr>
- </div>
- </body>
- </html>
This file contains the script for the page where the users can submit and edit the reply-to-comment.
- <?php require_once('Connection.php') ?>
- <?php
- echo "<script>alert('Comment ID is required.'); location.replace('./');</script>";
- exit;
- }
- ?>
- <!DOCTYPE html>
- <html lang="en">
- <head>
- <meta charset="UTF-8">
- <meta http-equiv="X-UA-Compatible" content="IE=edge">
- <meta name="viewport" content="width=device-width, initial-scale=1.0">
- <title>Simple Comment Section</title>
- <link rel="stylesheet" href="./css/bootstrap.min.css">
- <script src="./js/jquery-3.6.0.min.js"></script>
- <script src="./js/bootstrap.min.js"></script>
- <style>
- :root {
- --bs-success-rgb: 71, 222, 152 !important;
- }
- html,
- body {
- height: 100%;
- width: 100%;
- font-family: Apple Chancery, cursive;
- }
- </style>
- </head>
- <body class="bg-light">
- <nav class="navbar navbar-expand-lg navbar-dark bg-primary bg-gradient" id="topNavBar">
- <div class="container">
- <a class="navbar-brand" href="https://sourcecodester.com">
- Sourcecodester
- </a>
- </div>
- </nav>
- <div class="container py-3" id="page-container">
- <h3>Reply to</h3>
- <div class="alert alert-<?php echo $_SESSION['response_type'] ?>">
- <p class="m-0"><?php echo $_SESSION['response_msg'] ?></p>
- </div>
- <?php
- endif;
- ?>
- <hr>
- <?php
- $comment_qry = $conn->query("SELECT * FROM `comments` where comment_id = '{$_GET['comment_id']}' ");
- $result = $comment_qry->fetchArray();
- if(!$result){
- echo "<script>alert('Unkown Comment ID.'); location.replace('./');</script>";
- exit;
- }else{
- ?>
- <div class="card mb-2">
- <div class="card-body">
- <div class="d-flex align-items-end">
- </div>
- <hr>
- <div class="lh-1">
- <p class=""><span class="mx-3"></span><?php echo str_replace('\n','<br/>',$result['comment']) ?></p>
- </div>
- </div>
- </div>
- <?php } ?>
- <hr>
- <?php
- $reply_qry = $conn->query("SELECT * FROM `replies` where reply_id = '{$_GET['reply_id']}' ");
- $result2 = $reply_qry->fetchArray();
- if(!$result2){
- echo "<script>alert('Unkown Reply ID.'); location.replace('./');</script>";
- exit;
- }
- }
- ?>
- <form id="comment-form" action="save_reply.php" method="POST">
- <input type="hidden" name="reply_id" value="<?php echo isset($_GET['reply_id']) ? $_GET['reply_id'] : '' ?>" >
- <input type="hidden" name="comment_id" value="<?php echo $_GET['comment_id'] ?>" >
- <div class="form-group">
- <label for="sender" class="control-label">Sender</label>
- </div>
- <div class="form-group">
- <label for="reply" class="control-label">Reply</label>
- </div>
- <div class="form-group">
- <div class="col-12 mt-4">
- <div class="d-flex justify-content-end align-items-end">
- <button class="btn btn-sm btn-sm btn-primary rounded-0 me-2" type="submit">Save</button>
- <a class="btn btn-sm btn-sm btn-secondary rounded-0" href="./">Cancel</a>
- </div>
- </div>
- </div>
- </form>
- </div>
- </body>
- </html>
Creating the PHP Action Scripts
The following PHP Scripts are the files that manages the queries on the database. Theese are the saving,inserting, and deleting scripts for comments and replies. Save the following files according to the given filename above each file scripts.
The PHP Code that insert new comment or update old comment in the database.
- <?php
- require_once('Connection.php');
- }
- $sender = $_POST['sender'];
- $comment = $conn->escapeString($_POST['comment']);
- $sql = "INSERT INTO `comments` (`sender`,`comment`) VALUES ('{$sender}','{$comment}')";
- else
- $sql = "UPDATE `comments` set `sender` = '{$sender}' ,`comment` = '{$comment}' where comment_id = '$comment_id'";
- $save = $conn->query($sql);
- if($save){
- $_SESSION['response_type'] = 'success';
- $_SESSION['response_msg'] = 'Comment Successfully saved.';
- else
- }else{
- $_SESSION['response_type'] = 'danger';
- $_SESSION['response_msg'] = 'Saving comment failed. Error: '. $conn->lastErrorMsg();
- $_SESSION['comment-post'] = $_POST;
- }
The PHP Code that insert new reply or update old reply in the database.
- <?php
- require_once('Connection.php');
- }
- $comment_id = $_POST['comment_id'];
- $sender = $_POST['sender'];
- $reply = $conn->escapeString($_POST['reply']);
- $sql = "INSERT INTO `replies` (`comment_id`,`sender`,`reply`) VALUES ('{$comment_id}','{$sender}','{$reply}')";
- else
- $sql = "UPDATE `replies` set `sender` = '{$sender}' ,`reply` = '{$reply}' where reply_id = '$reply_id'";
- $save = $conn->query($sql);
- if($save){
- $_SESSION['response_type'] = 'success';
- $_SESSION['response_msg'] = 'Reply Successfully saved.';
- }else{
- $_SESSION['response_type'] = 'danger';
- $_SESSION['response_msg'] = 'Saving reply failed. Error: '. $conn->lastErrorMsg();
- $_SESSION['reply-post'] = $_POST;
- }
The PHP code for deleting comment.
- <?php
- require_once('Connection.php');
- $sql = "DELETE FROM `comments` where comment_id = '{$_GET['comment_id']}'";
- $delete = $conn->query($sql);
- if($delete){
- $_SESSION['response_type'] = 'success';
- $_SESSION['response_msg'] = 'Comment Successfully deleted.';
- else
- }else{
- $_SESSION['response_type'] = 'danger';
- $_SESSION['response_msg'] = 'Deleting comment failed. Error: '. $conn->lastErrorMsg();
- $_SESSION['comment-post'] = $_POST;
- }
- ?>
The PHP code for deleting reply.
- <?php
- require_once('Connection.php');
- $sql = "DELETE FROM `replies` where reply_id = '{$_GET['reply_id']}'";
- $delete = $conn->query($sql);
- if($delete){
- $_SESSION['response_type'] = 'success';
- $_SESSION['response_msg'] = 'Reply Successfully deleted.';
- else
- }else{
- $_SESSION['response_type'] = 'danger';
- $_SESSION['response_msg'] = 'Deleting reply failed. Error: '. $conn->lastErrorMsg();
- $_SESSION['reply-post'] = $_POST;
- }
- ?>
There you go. You can now test the source code on your end. If you have encountered any errors, kindly review your source code by differentiating it from the codes I provided above. You can also download the working source code I created for this tutorial. The download button is located below this article.
DEMO VIDEO
That's the end of this tutorial. I hope this Comment Section tutorial in PHP and SQLite will help you and useful for your PHP Projects.
Explore more on this website for more Tutorials and Free Source Codes.
Happy Coding :)
Comments
Add new comment
- Add new comment
- 2437 views