1//...
2// If the user clicked submit on comment form...
3if (isset($_POST['comment_posted'])) {
4 global $db;
5 // grab the comment that was submitted through Ajax call
6 $comment_text = $_POST['comment_text'];
7 // insert comment into database
8 $sql = "INSERT INTO comments (post_id, user_id, body, created_at, updated_at) VALUES (1, " . $user_id . ", '$comment_text', now(), null)";
9 $result = mysqli_query($db, $sql);
10 // Query same comment from database to send back to be displayed
11 $inserted_id = $db->insert_id;
12 $res = mysqli_query($db, "SELECT * FROM comments WHERE id=$inserted_id");
13 $inserted_comment = mysqli_fetch_assoc($res);
14 // if insert was successful, get that same comment from the database and return it
15 if ($result) {
16 $comment = "<div class='comment clearfix'>
17 <img src='profile.png' alt='' class='profile_pic'>
18 <div class='comment-details'>
19 <span class='comment-name'>" . getUsernameById($inserted_comment['user_id']) . "</span>
20 <span class='comment-date'>" . date('F j, Y ', strtotime($inserted_comment['created_at'])) . "</span>
21 <p>" . $inserted_comment['body'] . "</p>
22 <a class='reply-btn' href='#' data-id='" . $inserted_comment['id'] . "'>reply</a>
23 </div>
24 <!-- reply form -->
25 <form action='post_details.php' class='reply_form clearfix' id='comment_reply_form_" . $inserted_comment['id'] . "' data-id='" . $inserted_comment['id'] . "'>
26 <textarea class='form-control' name='reply_text' id='reply_text' cols='30' rows='2'></textarea>
27 <button class='btn btn-primary btn-xs pull-right submit-reply'>Submit reply</button>
28 </form>
29 </div>";
30 $comment_info = array(
31 'comment' => $comment,
32 'comments_count' => getCommentsCountByPostId(1)
33 );
34 echo json_encode($comment_info);
35 exit();
36 } else {
37 echo "error";
38 exit();
39 }
40}
41// If the user clicked submit on reply form...
42if (isset($_POST['reply_posted'])) {
43 global $db;
44 // grab the reply that was submitted through Ajax call
45 $reply_text = $_POST['reply_text'];
46 $comment_id = $_POST['comment_id'];
47 // insert reply into database
48 $sql = "INSERT INTO replies (user_id, comment_id, body, created_at, updated_at) VALUES (" . $user_id . ", $comment_id, '$reply_text', now(), null)";
49 $result = mysqli_query($db, $sql);
50 $inserted_id = $db->insert_id;
51 $res = mysqli_query($db, "SELECT * FROM replies WHERE id=$inserted_id");
52 $inserted_reply = mysqli_fetch_assoc($res);
53 // if insert was successful, get that same reply from the database and return it
54 if ($result) {
55 $reply = "<div class='comment reply clearfix'>
56 <img src='profile.png' alt='' class='profile_pic'>
57 <div class='comment-details'>
58 <span class='comment-name'>" . getUsernameById($inserted_reply['user_id']) . "</span>
59 <span class='comment-date'>" . date('F j, Y ', strtotime($inserted_reply['created_at'])) . "</span>
60 <p>" . $inserted_reply['body'] . "</p>
61 <a class='reply-btn' href='#'>reply</a>
62 </div>
63 </div>";
64 echo $reply;
65 exit();
66 } else {
67 echo "error";
68 exit();
69 }
70}
1$(document).ready(function(){
2 // When user clicks on submit comment to add comment under post
3 $(document).on('click', '#submit_comment', function(e) {
4 e.preventDefault();
5 var comment_text = $('#comment_text').val();
6 var url = $('#comment_form').attr('action');
7 // Stop executing if not value is entered
8 if (comment_text === "" ) return;
9 $.ajax({
10 url: url,
11 type: "POST",
12 data: {
13 comment_text: comment_text,
14 comment_posted: 1
15 },
16 success: function(data){
17 var response = JSON.parse(data);
18 if (data === "error") {
19 alert('There was an error adding comment. Please try again');
20 } else {
21 $('#comments-wrapper').prepend(response.comment)
22 $('#comments_count').text(response.comments_count);
23 $('#comment_text').val('');
24 }
25 }
26 });
27 });
28 // When user clicks on submit reply to add reply under comment
29 $(document).on('click', '.reply-btn', function(e){
30 e.preventDefault();
31 // Get the comment id from the reply button's data-id attribute
32 var comment_id = $(this).data('id');
33 // show/hide the appropriate reply form (from the reply-btn (this), go to the parent element (comment-details)
34 // and then its siblings which is a form element with id comment_reply_form_ + comment_id)
35 $(this).parent().siblings('form#comment_reply_form_' + comment_id).toggle(500);
36 $(document).on('click', '.submit-reply', function(e){
37 e.preventDefault();
38 // elements
39 var reply_textarea = $(this).siblings('textarea'); // reply textarea element
40 var reply_text = $(this).siblings('textarea').val();
41 var url = $(this).parent().attr('action');
42 $.ajax({
43 url: url,
44 type: "POST",
45 data: {
46 comment_id: comment_id,
47 reply_text: reply_text,
48 reply_posted: 1
49 },
50 success: function(data){
51 if (data === "error") {
52 alert('There was an error adding reply. Please try again');
53 } else {
54 $('.replies_wrapper_' + comment_id).append(data);
55 reply_textarea.val('');
56 }
57 }
58 });
59 });
60 });
61});
1form button { margin: 5px 0px; }
2textarea { display: block; margin-bottom: 10px; }
3/*post*/
4.post { border: 1px solid #ccc; margin-top: 10px; }
5/*comments*/
6.comments-section { margin-top: 10px; border: 1px solid #ccc; }
7.comment { margin-bottom: 10px; }
8.comment .comment-name { font-weight: bold; }
9.comment .comment-date {
10 font-style: italic;
11 font-size: 0.8em;
12}
13.comment .reply-btn, .edit-btn { font-size: 0.8em; }
14.comment-details { width: 91.5%; float: left; }
15.comment-details p { margin-bottom: 0px; }
16.comment .profile_pic {
17 width: 35px;
18 height: 35px;
19 margin-right: 5px;
20 float: left;
21 border-radius: 50%;
22}
23/*replies*/
24.reply { margin-left: 30px; }
25.reply_form {
26 margin-left: 40px;
27 display: none;
28}
29#comment_form { margin-top: 10px; }
1+----+-----------+--------------+------------+
2| field | type | specs |
3+----+-----------+--------------+------------+
4| id | INT(11) | |
5| user_id | INT(11) | |
6| post_id | INT(11) | |
7| body | TEXT | |
8| created_at | TIMESTAMP | |
9| updated_at | TIMESTAMP | |
10+----------------+--------------+------------+
1+----+-----------+------------------------+------------+
2| field | type | specs |
3+----+-----------+------------------------+------------+
4| id | INT(11) | |
5| username | VARCHAR(255) | UNIQUE |
6| email | VARCHAR(255) | UNIQUE |
7| password | VARCHAR(255) | |
8| created_at | TIMESTAMP | |
9+----------------+--------------+---------+------------+
1+----+-----------+--------------+------------+
2| field | type | specs |
3+----+-----------+--------------+------------+
4| id | INT(11) | |
5| user_id | INT(11) | |
6| comment_id | INT(11) | |
7| body | TEXT | |
8| created_at | TIMESTAMP | |
9| updated_at | TIMESTAMP | |
10+----------------+--------------+------------+
1+----+-----------+--------------+------------+
2| field | type | specs |
3+----+-----------+--------------+------------+
4| id | INT(11) | |
5| title | VARCHAR(255) | |
6| slug | VARCHAR(255) | UNIQUE |
7| body | TEXT | |
8| created_at | TIMESTAMP | |
9| updated_at | TIMESTAMP | |
10+----------------+--------------+------------+
1<?php include('functions.php'); ?>
2<!DOCTYPE html>
3<html lang="en">
4<head>
5 <meta charset="UTF-8">
6 <title>Comment and reply system in PHP</title>
7 <!-- Bootstrap CSS -->
8 <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/css/bootstrap.min.css" />
9 <link rel="stylesheet" href="main.css">
10</head>
11<body>
12<div class="container">
13 <div class="row">
14 <div class="col-md-6 col-md-offset-3 post">
15 <h2><?php echo $post['title'] ?></h2>
16 <p><?php echo $post['body']; ?></p>
17 </div>
18 <div class="col-md-6 col-md-offset-3 comments-section">
19 <!-- if user is not signed in, tell them to sign in. If signed in, present them with comment form -->
20 <?php if (isset($user_id)): ?>
21 <form class="clearfix" action="post_details.php" method="post" id="comment_form">
22 <textarea name="comment_text" id="comment_text" class="form-control" cols="30" rows="3"></textarea>
23 <button class="btn btn-primary btn-sm pull-right" id="submit_comment">Submit comment</button>
24 </form>
25 <?php else: ?>
26 <div class="well" style="margin-top: 20px;">
27 <h4 class="text-center"><a href="#">Sign in</a> to post a comment</h4>
28 </div>
29 <?php endif ?>
30 <!-- Display total number of comments on this post -->
31 <h2><span id="comments_count"><?php echo count($comments) ?></span> Comment(s)</h2>
32 <hr>
33 <!-- comments wrapper -->
34 <div id="comments-wrapper">
35 <?php if (isset($comments)): ?>
36 <!-- Display comments -->
37 <?php foreach ($comments as $comment): ?>
38 <!-- comment -->
39 <div class="comment clearfix">
40 <img src="profile.png" alt="" class="profile_pic">
41 <div class="comment-details">
42 <span class="comment-name"><?php echo getUsernameById($comment['user_id']) ?></span>
43 <span class="comment-date"><?php echo date("F j, Y ", strtotime($comment["created_at"])); ?></span>
44 <p><?php echo $comment['body']; ?></p>
45 <a class="reply-btn" href="#" data-id="<?php echo $comment['id']; ?>">reply</a>
46 </div>
47 <!-- reply form -->
48 <form action="post_details.php" class="reply_form clearfix" id="comment_reply_form_<?php echo $comment['id'] ?>" data-id="<?php echo $comment['id']; ?>">
49 <textarea class="form-control" name="reply_text" id="reply_text" cols="30" rows="2"></textarea>
50 <button class="btn btn-primary btn-xs pull-right submit-reply">Submit reply</button>
51 </form>
52
53 <!-- GET ALL REPLIES -->
54 <?php $replies = getRepliesByCommentId($comment['id']) ?>
55 <div class="replies_wrapper_<?php echo $comment['id']; ?>">
56 <?php if (isset($replies)): ?>
57 <?php foreach ($replies as $reply): ?>
58 <!-- reply -->
59 <div class="comment reply clearfix">
60 <img src="profile.png" alt="" class="profile_pic">
61 <div class="comment-details">
62 <span class="comment-name"><?php echo getUsernameById($reply['user_id']) ?></span>
63 <span class="comment-date"><?php echo date("F j, Y ", strtotime($reply["created_at"])); ?></span>
64 <p><?php echo $reply['body']; ?></p>
65 <a class="reply-btn" href="#">reply</a>
66 </div>
67 </div>
68 <?php endforeach ?>
69 <?php endif ?>
70 </div>
71 </div>
72 <!-- // comment -->
73 <?php endforeach ?>
74 <?php else: ?>
75 <h2>Be the first to comment on this post</h2>
76 <?php endif ?>
77 </div><!-- comments wrapper -->
78 </div><!-- // all comments -->
79 </div>
80</div>
81<!-- Javascripts -->
82<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
83<!-- Bootstrap Javascript -->
84<script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/js/bootstrap.min.js"></script>
85
86<script src="scripts.js"></script>
87</body>
88</html>