初学者需要帮助sql和php

时间:2011-02-11 19:55:16

标签: php sql mysql

我正在为我的网站制作一个简单的论坛,但我遇到了一些问题

它不打印帖子。我没有得到任何错误非常奇怪。它打印线程标题。

$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'];
}

表格:

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 :)');

3 个答案:

答案 0 :(得分:1)

检查您的查询和数据库连接是否成功。你没有这样做,所以现在如果查询失败,它会默默地这样做,你就陷入了黑暗中:

$result = mysql_query($query) or die(mysql_error());

开发过程中的那些东西可以为你节省大量的时间和精力。

答案 1 :(得分:0)

第一条消息在$ row中试试这个

// 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

答案 2 :(得分:0)

你可能想要这样的东西:

$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'];
}

请注意ORDER BY子句和$lastTID位。