Reputation: 3
I have looked far and wide through the lands of Stack Overflow, but have found no success in finding a solution to my extremely basic question.
I have a messaging system within my website and when a user posts a message, I would like their name to feature at the top of the article eg. "Posted by (name)".
At the moment, it displays the name of the logged in user, however this name changes depending on whoever is logged in at the time.
So, if I posted something under the name "Jim", and then logged in under the name "Bob", it would display the poster name as "Bob".
I am aware that my problem lies within $username = $_SESSION['username'];
. I'm just not sure what to do about it.
<?php
require_once("nbbc/nbbc.php");
$bbcode = new BBCode;
$sql = "SELECT * FROM comment ORDER BY id DESC";
$res = mysqli_query($dbCon, $sql) or die(mysqli_error($dbCon));
$comment = "";
$username = $_SESSION['username'];
if(mysqli_num_rows($res) > 0) {
while($row = mysqli_fetch_assoc($res)) {
$id = $row['id'];
$date = $row['date'];
$content = $row['content'];
$bbcode->Parse($content);
$comment .= "
<div id='a_comment'>
<h1>Posted by $username on $date</h1>
<p>$content</p>
</div>
";
}
echo $comment;
} else {
echo "<div id='no_comments'>There are no comments to be displayed.</div>";
}
?>
Here's the rest of the code:
<?php
session_start();
include_once("inc/connection.php");
error_reporting(E_ALL); ini_set('display_errors', 1);
if(!isset($_SESSION['username'])) {
header("Location: login.php");
return;
}
if(isset($_POST['post'])) {
$content = strip_tags($_POST['content']);
$content = mysqli_real_escape_string($dbCon, $content);
date_default_timezone_set("Australia/Victoria");
$date = date('d-m-y h:i:sa');
$sql = "INSERT INTO comment (date, content) VALUES ('$date', '$content')";
mysqli_query($dbCon, $sql);
header("Location: members.php");
}
?>
Upvotes: 0
Views: 66
Reputation: 5125
Ideally you would store the user ID in the comment
table, and then use the user table for a lookup when pulling the comment out. However, since I know nothing about your table structure, I'm going to give you instructions for storing the username in the comment
table instead, and you can adjust for your needs.
Step 1: Alter your comment
table to store the username
ALTER TABLE comment
ADD username VARCHAR(100) AFTER content;
Step 2: Store the username when storing the post
$sql = "INSERT INTO comment (date, content, username) VALUES ('$date', '$content', '{$_SESSION['username']}')";
Step 3: Assign the correct username when retrieving the data
$username = $row['username'];
Upvotes: 1