Hello,
I’m new to PHP (only started learning 2 days ago) and i’ve created a little blog system which displays the 5 latest blog posts which are in a mysql database.
I tried adding a comment system which displays the last 5 comments for each post but its only showing 1 comment on the page, even though more than one blog post has a comment.
Here is my code for blog.php
[php]<?
session_start();
$myusername = $_SESSION[‘myusername’];
$db_host = ‘localhost’;
$db_user = ‘HIDDEN’;
$db_pwd = ‘HIDDEN’;
$database = ‘tjwebsol_dev’;
$table = ‘posts’;
$table2 = ‘blog_comments’;
$tab = ‘            ’;
if (!mysql_connect($db_host, $db_user, $db_pwd))
die(“Can’t connect to database”);
if (!mysql_select_db($database))
die(“Can’t select database”);
// sending query
$result = mysql_query(“SELECT * FROM {$table} ORDER BY blog_id DESC LIMIT 5”);
if (!$result) {
die(“Query to show fields from table failed”);
}
$sql = mysql_query("SELECT * FROM {$table2} ORDER BY comment_id ASC LIMIT 5 ");
$fields_num = mysql_num_fields($result);
$fields_num2 = mysql_num_fields($sql);
while($row2 = mysql_fetch_assoc($sql))
{
$blog_comments = $row2[‘comment_content’];
$date_commented = $row2[‘date_commented’];
$time_commented = $row2[‘time_commented’];
$blog_username2 = $row2[‘username’];
$blogid = $row2[‘blogid’];
$comment_id = $row2[‘comment_id’];
}
while($row = mysql_fetch_assoc($result))
{
$blog_title = $row[‘title’];
$blog_content = $row[‘content’];
$blog_username = $row[‘username’];
$blog_date = $row[‘date_posted’];
$blog_time = $row[‘time_posted’];
$blog_id = $row[‘blog_id’];
echo “
”;
echo “
echo “
$blog_title
”;echo “
posted by $blog_username on $blog_date ($blog_time)
”;echo “
”;
echo “
”;
if ($blogid == $blog_id)
{
echo “User Posted Comments:
”;
echo “$tab$comment_id. $blog_comments”;
echo “
”;
echo “Commented posted by $blog_username2 on $date_commented ($time_commented)”;
echo “
”;
}
if (!isset($_SESSION[‘logged’])
|| $_SESSION[‘logged’] !== true) {
// not logged in, move to login page
echo "<b><a href='login.php'>Login</a></b> to post your comments!";
}
echo "<br><br><br>";
include('blognewcomment.php');
echo "";
echo "</div>";
}
mysql_free_result($result);
?>[/php]
Also, here are 2 screenshots of the database tables it uses.
posts is where the blog posts are kept and comments for comments.