Set username as author of comment in php/mysql

Viewed 54

So I'm making a website where registered users are able to make a post, comment on the post as well as reply to the comments and I'm having trouble with displaying the username of whom has commented.

File home.php

<?php
$sql = "SELECT * FROM post LIMIT 3";
$result = $conn->query($sql);
while ($row = mysqli_fetch_assoc($result)){
    $id = $row['users_id'];
    $sql2 = "SELECT * FROM users WHERE users_username='$id'";
    $result2 = $conn->query($sql2);
    if($row2 = mysqli_fetch_assoc($result2)){
        echo "<div class='comment-box'>";
        echo $row['title']."<br>";
        echo $row['date_created']."<br>";
        echo $row2['users_id']."<br>";
        echo $row['content']."<br>";           
        echo "</p></div>";
        if(isset ($_SESSION["username"])){
            echo "<button type='button' id='postbtn' onclick='replyFunction()'>Reply</button>";
            include 'commentsection.php';      
        } 
    }
}

File makeapost.php

<div class="thread">
<form action="<?php echo htmlspecialchars("includes/posts.inc.php");?>"method="post">
    <h4>Create a post </h4>
    <hr></hr>
    <input type="hidden" name="post_id">
    <input type="hidden" name="users_id" value="<?php echo ".$_SESSION[username].";?>">
    <input type="text" id="thetitle" name="title" placeholder="Title">
    <input type="hidden"  name="date_created"> <br>
    <textarea id="summernote" name="content"></textarea>
    <hr></hr>
    <button type="submit" id="postbutton" name="submit">Post</button>
    
  </form>
</div>

File posts.inc.php

<?php
include 'dbh.inc.php';
include 'functions.inc.php';

if (isset($_POST["submit"])){
    $title = $_POST["title"];
    $users_id = $_POST["users_id"];
    $content = $_POST["content"];
    $date_created = $_POST["date_created"];
    $mysqltime = date ('Y-m-d H:i:s');

    
    $sql = "INSERT INTO post (title, users_id, content, date_created) VALUES (?,?,?,?);";

    $stmt = mysqli_stmt_init($conn);
 
    if (!mysqli_stmt_prepare($stmt, $sql)){
     header("location: ../home.php?error=stmtfailed");
     exit();
    }

    mysqli_stmt_bind_param($stmt, "ssss", $title, $users_id, $content, $mysqltime);
    mysqli_stmt_execute($stmt);
    mysqli_stmt_close($stmt);
    header("location: ../home.php?error=none");
     exit();
    
}

login.inc.php

<?php

if (isset($_POST ["submit"])){
    $username = $_POST["username"];
    $password = $_POST["password"];

    require_once 'dbh.inc.php';
    require_once 'functions.inc.php';

    if(emptyInputLogin($username, $password) !== false){
        header("location: ../home.php?error=emptyinput");
        exit();
    }

    loginUser($conn, $username, $password);

} else {
    header("location: ../home.php");
    exit();
}

functions.inc.php

function loginUser($conn, $username, $password){
    $uidExists = uidExists($conn, $username, $username);

    if($uidExists === false){
        header("location: ../login.php?error=wrongusername");
        exit();
    }

    $passwordHashed = $uidExists["users_password"];
    $checkPwd = password_verify($password, $passwordHashed);

    if($checkPwd === false){
        header("location: ../login.php?error=wrongpassword");
        exit();
    } else if ($checkPwd === true){
        session_start();
        $_SESSION["userid"] = $uidExists["users_id"];
        $_SESSION["username"] = $uidExists["users_username"];
        $_SESSION["role"] = $uidExists["users_role"];
        header("location: ../home.php");
        exit();
    }
}

Table structure

CREATE TABLE IF NOT EXISTS `post` (
  `post_id` int(11) NOT NULL AUTO_INCREMENT,
  `users_id` int(11) NOT NULL,
  `content` varchar(500) NOT NULL,
  `date_created` varchar(500) NOT NULL,
  PRIMARY KEY (`post_id`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=14;

CREATE TABLE IF NOT EXISTS `users` (
  `users_id` int(11) NOT NULL AUTO_INCREMENT,
  `users_username` tinytext NOT NULL,
  `users_password` longtext NOT NULL,
  PRIMARY KEY (`users_id`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=6 ;

It may have something to do with the fact that I cannot connect the right user ID from the post table to the users table, since in the users table i have columns such as (users_id(AUTO_INCREMENT), users_username) but in post table i have (users_id). I am able to make a post and messages are inserted to the database, but theres no users shown.

Any tips on how I can improve this? Right now nothing is being displayed on home.php page, but the posts are still in the database.

1 Answers

Working from the table definitions you posted above (which don't match your PHP code) I created this data:

post table:

post_id users_id content dateCreated
14 6 Here's some content 20 May 2022
15 7 A message 19 May 2022
16 7 Another message 20 May 2022
17 8 I've nothing to say 20 May 2022
18 9 I said everything already. 18 May 2022

Users table

users_id users_username users_password
6 Mike password
7 George another password
8 Helen passwd
9 Alice pword
10 Bob secret

From this I created this query:

select post_id, content, date_created, u.users_username 
    from 
        post 
    join 
        (select users_username, users_id from users) u 
    on post.users_id = u.users_id
order by date_created desc
limit 3;

Which gives this result:

post_id content date_created users_username
14 Here's some content 20 May 2022 Mike
16 Another message 20 May 2022 George
17 I've nothing to say 20 May 2022 Helen

Now you can just loop through the results and create your output without the need for a nested query to retrieve data.

Note:

  • This is a simple example based on your table structure and some simple data. You can include or exclude some of these columns, change the order, include or exclude more rows.
  • dateCreated should be a DateTime column, not a varchar column
  • Passwords should NOT be stored in plain text.
  • You will need to consider appropriate indexing once these tables start to grow.
Related