php - 我该如何改进这段代码?

标签 php mysql

我可以只使用 1 个 sql 查询吗?

showthread.php

// Get Topic subject etc
$threadID = isset($_GET['threadID']) ? intval($_GET['threadID']) : 0;
$result = mysql_query("SELECT * FROM topics WHERE id = $threadID");

// Fetch rows
$row = mysql_fetch_assoc($result);
$subject = htmlspecialchars($row['subject']);

echo '<h2>'.$subject.'</h2>';


// Get posts that belong to this topic!
$posts = mysql_query("SELECT * FROM posts INNER JOIN users ON users.id = posts.user_id WHERE posts.topic_id = $threadID");

// posts.....
while ($post = mysql_fetch_assoc($posts)) {
    echo '<br>'.$post['message'].'';
}

最佳答案

根据我的理解,你应该能够从这样的东西中获得你需要的所有信息? (加上或减去任何缺失的列)

SELECT topics.subject, posts.message
FROM posts 
INNER JOIN users ON users.id = posts.user_id
INNER JOIN topics ON topics.id = posts.topic_id
WHERE posts.topic_id = $threadID

关于php - 我该如何改进这段代码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6259892/

相关文章:

php - 多个单选按钮ajax post

javascript - 在 foreach 循环内提交特定表单

php - 将每个数组值作为单独的行插入 codeigniter 从 Controller 到模型

php - PHP/JavaScript/.NET 中的 MAC 地址?

PHP SQL 查询返回随机字符

mysql - 通过桌面快捷方式执行mysql命令?

mysql - 将包含日期的 Varchar 转换为 DATETIME

php - Codeception\Util\Stub 方法::exactly 和::once 不起作用

php - 等待 ajax 完成后离开页面

mysql - 使值等于平均值