0

I have an application that where users can post announcements and comment on posts. My problem is that whenever a comment is posted, It shows up on every announcement post. How can I post comments so that they show up on that specific post?

I have 2 database tables: "announcement: id, name, announcementTitle, announcement, image" and "comment: id, post_id, name, comment" with foreign key attached to comment.

Here is my home.php where the announcements and comments are echoed

<div class="container">
            <div class="mx-auto">
                <?php 
                if (isset($_SESSION['username'])) {
                
                    echo'
                <h1 style="text-decoration:underline">Post an announcement</h1>
                <form method="post" action="announcement.php" enctype="multipart/form-data">
                    <input type="text" name="announcementTitle" placeholder="Enter Subject"><br>
                    <textarea name="announcementBox" rows="5" cols="40" placeholder="Enter Announcement"></textarea><br>
                    <input type="file" name="image" accept="image/jpeg">
                    <button name="announcement">Submit</button>
                </form>';
                    
                }
                $query = "SELECT * FROM announcement ORDER BY id DESC";
                $result = mysqli_query($con,$query);
                while ($row = mysqli_fetch_array($result)) {
                    echo '<div class="row" style="color:black;background-color:white;border-radius:5px;padding:10px;margin-top:10px;margin-bottom:70px">';
                    echo '<div class="column" style="width:100%;border:5px">';
                    if (isset($_SESSION['username'])) {
                        
                        echo '<form method="post" action="announcement.php">';
                        echo "Posted by " .$row["name"]. " click X to delete:";
                        echo '<input type="hidden" name="postID" value="'.$row['id'].'">';
                        echo '<button name="delete" style="float:right">X</button>';
                        echo '</form>';
                    
                    }
                    echo $row['announcementTitle'].'<br>';
                    echo $row['announcement'].'<br>';
                    echo '<img width="20%" src="data:image;base64,'.$row['image'].'"alt="Image" style="padding-top:10px">';
                    echo'
                    <form method="post" action="comment.php">
                        <textarea name="commentbox" rows="2" cols="50" placeholder="Leave a Comment"></textarea><br>
                    
                        <button name="comment">Submit</button>
                    </form>';
                    echo "Comments:<p><p>";
                    echo " <p>";
                    $find_comment = "SELECT * FROM comment ORDER BY id DESC";
                    $res = mysqli_query($con,$find_comment);
                    while ($row = mysqli_fetch_array($res)) {
                        echo '<input type="hidden" name="postID" value="'.$row['post_id'].'">';
                        $comment_name = $row['name'];
                        $comment = $row['comment'];
                        echo "$comment_name: $comment<p>";
                    }
                    if(isset($_GET['error'])) {
                        echo "<p>100 Character Limit";
                    }
                    echo '</div></div>';
                
                    }
                
                ?>
            </div>
        </div>

Here is comment.php where comments are put in the database

<?php

session_start();


$con = mysqli_connect('localhost', 'root', 'Arv5n321');

mysqli_select_db($con, 'userregistration');

$namee = '';
$comment = '';

$comment_length = strlen($comment);

if($comment_length > 100) {
    header("location: home.php?error=1");
}else {
    $que = "SELECT * FROM announcement";
    $res = mysqli_query($con,$que);
    while ($row = mysqli_fetch_array($res)) {
        $post_id = $row['id'];
    }
    $namee = $_SESSION['username'];
    $comment = $_POST['commentbox'];
    $query = "INSERT INTO comment(post_id,name,comment) VALUES('$post_id','$namee','$comment')";
    $result = mysqli_query($con, $query);
    if ($result) {
    header("location:home.php?success=submitted");
    } else {
        header("location:home.php?error=couldnotsubmit");
    }
}



?>

Here is announcement.php where announcements are put in the database

<?php
session_start();
//$con = mysqli_connect('freedb.tech', 'freedbtech_arvindra', 'Arv5n321', 'freedbtech_remote') or die(mysqli_error($con));
$con = mysqli_connect('localhost', 'root', 'Arv5n321', 'userregistration') or die(mysqli_error($con));

if (isset($_POST['announcement'])) {
    $image = $_FILES['image']['tmp_name'];
    $name = $_FILES['image']['name'];
    $image = base64_encode(file_get_contents(addslashes($image)));
    date_default_timezone_set("America/New_York");
    $title = $_POST['announcementTitle']." (<b>".date("m/d/Y")." ".date("h:i:sa")."</b>)";
    $paragraph = $_POST['announcementBox'];
if (empty($paragraph)||empty($title)) {
    header('location:home.php?error=fillintheblanks');

}else{
    $nam = $_SESSION['username'];
    $query = "insert into announcement(name,announcementTitle,announcement,image) values('$nam','$title','$paragraph','$image')";
    $result = mysqli_query($con, $query);
    if ($result) {
    header("location:home.php?success=submitted");
    } else {
        header("location:home.php?error=couldnotsubmit");
    }
}
}else if (isset($_POST['delete'])){
    $query = "delete from announcement where id='".$_POST['postID']."';";
    $result = mysqli_query($con,$query);
    if ($result) {
        header('location:home.php?success=deleted');
    } else {
        header('location:home.php?error=couldnotdelete');
    }
}
    else {
    header('location:home.php');
}

I am a little new to PHP so any help is good.

A P
  • 9
  • 2
  • There are (at least) 2 logic errors here. 1. In comment.php it makes no sense to select the post_id from the database - the way you've written it, it will always select the last one. The post ID should be one of the variables sent in the request when the comment is submitted, and be found in $_POST when PHP is processing the comment – ADyson Apr 21 '21 at 23:33
  • 1
    2. In home.php you just select all the comments for every announcement. Instead you need to restrict the query to only the ones relevant to the announcement being displayed at that time. E.g. `$find_comment = "SELECT * FROM comment WHERE post_id = ".$row["id"]." ORDER BY id DESC"` – ADyson Apr 21 '21 at 23:36
  • 1
    P.s. someone could crash your insert queries simply by putting an apostrophe in the announcement or comment text! And all your queries are vulnerable to SQL injection attacks. I don't know where you learned how to write SQL queries using PHP but they should have taught you to use prepared statements and parameters for these kinds of queries, especially ones which accept user input into them. It's negligent if you weren't shown that. See https://phpdelusions.net/mysqli for some simple examples of how to write them correctly so they are more robust and secure. – ADyson Apr 21 '21 at 23:48
  • 1
    **Warning:** You are wide open to [SQL Injections](https://php.net/manual/en/security.database.sql-injection.php) and should use parameterized **prepared statements** instead of manually building your queries. They are provided by [PDO](https://php.net/manual/pdo.prepared-statements.php) or by [MySQLi](https://php.net/manual/mysqli.quickstart.prepared-statements.php). Never trust any kind of input! Even when your queries are executed only by trusted users, [you are still in risk of corrupting your data](http://bobby-tables.com/). [Escaping is not enough!](https://stackoverflow.com/q/5741187) – Dharman Apr 22 '21 at 10:51

0 Answers0