Im making a simple forum for my site but im having some problems
it wont print the posts. and i get no error very weird. It prints the thread title.
$id = isset($_GET['t']) ? intval($_GET['t']) : 0;
$query = "SELECT * FROM threads t INNER JOIN posts p ON p.tid = t.id WHERE t.id = $id";
$result = mysql_query($query);
// see if thread exists
if (!mysql_num_rows($result)) {
echo "The requested thread does not exist.";
return false;
}
// Fetch the rows
$row = mysql_fetch_assoc($result);
// Print title
echo '<h1>'.htmlspecialchars($row['title']).'</h1>';
// Print posts
while ($row2 = mysql_fetch_assoc($result)) {
echo $row2['message'];
}
The Tables:
CREATE TABLE IF NOT EXISTS `threads` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`title` varchar(255) NOT NULL,
PRIMARY KEY (`id`)
)
INSERT INTO `threads` (`id`, `title`) VALUES
(1, 'My first thread!');
CREATE TABLE IF NOT EXISTS `posts` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`tid` int(10) unsigned NOT NULL DEFAULT '0',
`message` text NOT NULL,
PRIMARY KEY (`id`)
)
INSERT INTO `posts` (`id`, `tid`, `message`) VALUES
(1, 1, 'This is my first post in my first thread :)');
Check if your queries and db connections succeed. You're not doing that, so right now if the query fails, it'll do so silently and you're stuck in the dark:
$result = mysql_query($query) or die(mysql_error());
Something like that during development will save you a ton of hair and time.
the first message is in $row try this
// Fetch the rows
$row = mysql_fetch_assoc($result);
// Print title
echo '<h1>'.htmlspecialchars($row['title']).'</h1>';
echo $row['message'];
// Print posts
while ($row2 = mysql_fetch_assoc($result)) {
if($row['title'] == $row2['title'])
echo $row2['message'];
else
//start a new title
You probably want something like this:
$query = "SELECT * FROM threads t INNER JOIN posts p ON p.tid = t.id WHERE t.id = $id ORDER BY `tid` ASC";
$result = mysql_query($query);
if (!mysql_num_rows($result)) {
echo "The requested thread does not exist.";
return false;
}
$lastTID = null;
while ($row = mysql_fetch_assoc($result)) {
if ($lastTID != $row['tid']) {
echo '<h1>'.htmlspecialchars($row['title']).'</h1>';
$lastTID = $row['tid'];
}
echo $row['message'];
}
Note the ORDER BY
clause and the $lastTID
bit.