Counting Likes in PHP/OOP Tutorial
In this tutorial, I will show the simplest way to Count Likes of Posts in PHP and MySQL Database. Here, you will learn how to join a total count of rows from another table in a query. I will be providing a simple source code of a simple blog application that illustrate our main goal for this tutorial
About the Tutorial Application
The source code output a simple blog posting web application that allows the user to post content that is visible to other users. Each post contains a Thumbs Up or Like Icon that shows only an outline if the user hasn't liked the post yet while it displays the icon with filled color for the liked post. The total number of likes of each post is shown beside each like icon of the posts. Users don't need to register on the application. They can simply log in with a random user name and this feature is for demo purposes only.
Getting Started
In this tutorial, I used XAMPP v3.2.4 and Bootstrap v5 Framework on developing the source code. Kindly download the following so you can test the source code on your local machine. In my case, all CSS (Cascading Style Sheet) files are complied on a CSS directory while the JavaScript files are located at the JS directory.
You can download the Virtual Server and Library I used at:
- https://apachefriends.org for the XAMPP
- https://getbootstrap.com for the Bootstrap Framework
After download installing the server and library. Open your XAMPP's Control Panel and start the Apache and the MySQL servers.
Creating the Database
Open yout preferred browser such as Chrome Browser. Next, browse localhost/phpmyadmin and create a new database naming dummy_db. Then, navigate the page at the SQL Page and copy/paste the following sql code on the given text field and click the "Go" button.
- ADD CONSTRAINT `post_id_fk_ll` FOREIGN KEY (`post_id`) REFERENCES `post_list` (`id`) ON DELETE CASCADE ON UPDATE NO ACTION;
Creating the Database Connection
Open your preferred text editor such as notepad++ or sublime text. Create a new PHP File naming db-connect.php and save it inside your source code folder. Then, copy/paste the PHP script below and save the file.
- <?php
- $host = "localhost";
- $username = "root";
- $pw = "";
- $dbname = "dummy_db";
- $conn = new mysqli($host, $username, $pw, $dbname);
- if(!$conn){
- }
Creating the Login Page Interface
Create a new PHP File on your text editor naming login.php and save it also to yout source code folder. Then, copy/paste the source code below and save the file. This contains the html scripts of the application's login page elements and PHP script for login form submission.
- <!--
- This is a simple Web App. This was developed for educational purposes only.
- Author: oretnom23
- Email: [email protected]
- -->
- <?php
- // Require/Include DB Connection
- require_once('./db-connect.php');
- if($_SERVER['REQUEST_METHOD'] == 'POST'){
- $_SESSION['session_name'] = $_POST['session_name'];
- }
- ?><!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>PHP Counting Likes</title>
- <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.1.1/css/all.min.css" integrity="sha512-KfkfwYDsLkIlwQp6LFnl8zNdLGxu9YAA1QvwINks4PhcElQSvqcyVLLD9aMhXd13uQjoXtEKNosOWaZqXgel0g==" crossorigin="anonymous" referrerpolicy="no-referrer" />
- <link rel="stylesheet" href="./css/bootstrap.min.css">
- <script src="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.1.1/js/all.min.js" integrity="sha512-6PM0qYu5KExuNcKt5bURAoT6KCThUmHRewN3zUFNaoI6Di7XJPTMoT6K0nsagZKk2OB4L7E3q1uQKHNHd4stIQ==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
- <script src="./js/bootstrap.min.js"></script>
- </head>
- <style>
- html, body{
- height:100%;
- width:100%;
- }
- main{
- height:calc(100%);
- width:calc(100%);
- display:flex;
- flex-direction:column;
- align-items:center;
- justify-content:center
- }
- </style>
- <body class="bg-gradient bg-dark bg-opacity-50">
- <script>
- start_loader()
- </script>
- <main>
- <div class="col-lg-12">
- <h1 class="fw-bolder text-center" id="project-title">PHP Counting Likes</h1>
- </div>
- <div class="col-lg-6 col-md-8 col-sm-12 col-xs-12">
- <div class="card rounded-0">
- <div class="card-header">
- <h4 class="card-title text-center">Login</h4>
- </div>
- <div class="card-body">
- <div class="container-fluid">
- <form action="login.php" method="POST">
- <div class="form-group">
- <label for="session_name" class="control-label">Username</label>
- <input type="text" class="form-control form-control-sm rounded-0" id="session_name" name="session_name" placeholder="jsmith" required="required">
- </div>
- <div class="form-group text-end my-3">
- <button class="btn btn-primary btn-sm bg-gradient-primary rounded-0">Login</button>
- </div>
- </form>
- </div>
- </div>
- </div>
- </div>
- </main>
- </body>
- </html>
Creating the Main Interface
Create a new PHP File on your text editor naming index.php and save it also on your source code folder. Copy/Paste the script below and save the file. This file contains the Main Page HTML Elements and other PHP scripts for the for database queries and processes.
- <!--
- This is a simple Web App. This was developed for educational purposes only.
- Author: oretnom23
- Email: [email protected]
- -->
- <?php
- // Require/Include DB Connection
- require_once('./db-connect.php');
- }
- if($_SERVER['REQUEST_METHOD'] == 'POST'){
- $sql = "INSERT INTO `post_list` (`title`, `author`, `content`) VALUES ('{$conn->real_escape_string($title)}','{$conn->real_escape_string($session_name)}', '{$conn->real_escape_string($content)}')";
- $save= $conn->query($sql);
- if($save){
- echo "<script> alert('Post has been inserted successfully.'); location.replace('index.php'); </script>";
- }else{
- echo "<script> alert('Post has failed to insert. Error: '.$conn->error); location.replace('index.php'); </script>";
- }
- echo "<script> location.replace('index.php'); </script>";
- }
- $get = $conn->query("SELECT * FROM `like_list` where post_id = '{$post_id}' and session_name = '{$_SESSION['session_name']}'");
- if($get->num_rows > 0){
- $sql = "DELETE FROM `like_list` where post_id = '{$post_id}' and session_name = '{$_SESSION['session_name']}' ";
- }else{
- $sql = "INSERT INTO `like_list` set post_id = '{$post_id}', session_name = '{$_SESSION['session_name']}' ";
- }
- $process= $conn->query($sql);
- if($process){
- echo "<script> alert('Post Like has been updated.'); location.replace('index.php'); </script>";
- }else{
- echo "<script> alert('Post Like/Unlike has failed.'); location.replace('index.php'); </script>";
- }
- }
- $sql = "DELETE FROM `post_list` where id = '{$delete_post}'";
- $delete = $conn->query($sql);
- if($delete){
- echo "<script> alert('Post has been deleted successfully.'); location.replace('index.php'); </script>";
- }else{
- echo "<script> alert('Post has failed to delete. Error: '.$conn->error); location.replace('index.php'); </script>";
- }
- }
- ?><!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>PHP Counting Likes</title>
- <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.1.1/css/all.min.css" integrity="sha512-KfkfwYDsLkIlwQp6LFnl8zNdLGxu9YAA1QvwINks4PhcElQSvqcyVLLD9aMhXd13uQjoXtEKNosOWaZqXgel0g==" crossorigin="anonymous" referrerpolicy="no-referrer" />
- <link rel="stylesheet" href="./css/bootstrap.min.css">
- <script src="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.1.1/js/all.min.js" integrity="sha512-6PM0qYu5KExuNcKt5bURAoT6KCThUmHRewN3zUFNaoI6Di7XJPTMoT6K0nsagZKk2OB4L7E3q1uQKHNHd4stIQ==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
- <script src="./js/bootstrap.min.js"></script>
- </head>
- <style>
- html, body{
- height:100%;
- width:100%;
- }
- </style>
- <body class="bg-gradient bg-dark bg-opacity-50">
- <script>
- start_loader()
- </script>
- <nav class="navbar navbar-expand-sm navbar-dark bg-gradient bg-dark">
- <div class="container-fluid">
- <a class="navbar-brand" href="./">PHP Counting Likes</a>
- <div>
- <a href="./?logout=true" class="text-light fw-bolder text-decoration-none"><i class="fa fa-sign-out"></i> <?= $_SESSION['session_name'] ?></a>
- </div>
- </div>
- </div>
- </nav>
- <main>
- <div class="container w-100 mt-3">
- <div class="d-flex w-100 align-items-center mb-3">
- <div class="col-auto flex-shrink-1 flex-grow-1">
- <h3 class="text-center fw-bolder text-light">Posts</h3>
- </div>
- <div class="col-auto">
- <button class="btn btn-primary btn-sm bg-gradient rounded-0" type="button" data-bs-toggle="modal" data-bs-target="#postFormModal"><i class="fa fa-plus"></i> Add Post</button>
- </div>
- </div>
- <?php
- $posts = $conn->query("SELECT *,COALESCE((SELECT COUNT(id) FROM like_list where post_id = post_list.id), 0) as `likes` FROM `post_list` order by unix_timestamp(date_created) desc");
- while($row = $posts->fetch_assoc()):
- $is_liked = $conn->query("SELECT * FROM `like_list` where post_id = '{$row['id']}' and session_name = '{$_SESSION['session_name']}'")->num_rows;
- ?>
- <div class="card card-default rounded-0 mb-4">
- <div class="card-header py-1">
- <div class="card-title fw-light text-muted d-flex w-100">
- <div class="col-auto flex-shricnk-1 flex-grow-1"><?= $row['author'] ?></div>
- </div>
- </div>
- <div class="card-body">
- <h3 class="fw-bolder"><?= $row['title'] ?></h3>
- <div>
- <?= $row['content'] ?>
- </div>
- </div>
- <div class="card-footer py-1">
- <div class="d-flex w-100">
- <div class="col-auto flex-shrink-1 flex-grow-1">
- <?php if($is_liked > 0): ?>
- <a href="index.php?post_id=<?= $row['id'] ?>" class="text-decoration-none text-reset me-3"><i class="fa fa-thumbs-up text-primary"></i></a>
- <?php else: ?>
- <a href="index.php?post_id=<?= $row['id'] ?>" class="text-decoration-none text-reset me-3"><i class="far fa-thumbs-up"></i></a>
- <?php endif; ?>
- <span class="fw-bolder"><?= $row['likes'] ?> Like<?= $row['likes'] > 1 ? "s" : "" ?></span>
- </div>
- <div class="col-auto">
- <?php if($_SESSION['session_name'] == $row['author']): ?>
- <a href="./?delete_post=<?= $row['id'] ?>" onclick="if(confirm('Are you sure to delete this post?') == false){ event.preventDefault() }" class="btn btn-flat btn-danger rounded-0"><i class="fa fa-trash"></i> Delete</a>
- <?php endif; ?>
- </div>
- </div>
- </div>
- </div>
- <?php endwhile; ?>
- </div>
- <div class="modal fade" id="postFormModal" data-bs-backdrop="static" data-bs-keyboard="false" tabindex="-1" aria-labelledby="postFormModallabel" aria-hidden="true">
- <div class="modal-dialog modal-dialog-centered modal-dialog-scrollable modal-lg">
- <div class="modal-content rounded-0">
- <div class="modal-header">
- <h5 class="modal-title" id="postFormModallabel">New Member Form</h5>
- <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
- </div>
- <div class="modal-body">
- <form action="index.php" method="POST" id="new_post">
- <input type="hidden" name="session_name" value="<?= $_SESSION['session_name'] ?>">
- <div class="border-top border-bottom item py-2">
- <div class="form-group mb-3">
- <label for="title" class="control-label">Title</label>
- <input type="text" class="form-control form-control-sm rounded-0" id="title" name="title" required="required">
- </div>
- <div class="form-group mb-3">
- <label for="content" class="control-label">Content</label>
- <textarea rows="4" class="form-control form-control-sm rounded-0" id="content" name="content" required="required"></textarea>
- </div>
- </div>
- </form>
- </div>
- <div class="modal-footer">
- <button type="submit" class="btn btn-primary btn-sm rounded-0" form="new_post">Save Post</button>
- <button type="button" class="btn btn-secondary btn-sm rounded-0" data-bs-dismiss="modal">Close</button>
- </div>
- </div>
- </div>
- </div>
- </main>
- </body>
- </html>
There you go! You can now test the application on your end and see if it meets our goal for this tutorial. If there's an error occurred on your side, please review your changes with the source code I provided above. Or, you can also download the working source code I created for this tutorial. The download button for the source code zip file is located below this article.
DEMO VIDEO
That's the end of this tutorial. I hope this will help you with what you are looking for and for your future PHP Projects. Explore more on this website for more Tutorials and Free Source Codes.
Happy Coding!!!
Comments
Add new comment
- Add new comment
- 2154 views