我目前正在尝试开发一个小型CMS,但我在实施类别系统时遇到了困难。
我目前有一个循环显示表CLASSES中的所有行。
当它到达每行的CATEGORYID列时,我需要CATEGORYID将自己与来自CATCLASSES的外键ID相匹配,然后显示NAME。
// connect to the database
include('../include/connect-db.php');
// get results from database
$result = mysql_query("SELECT * FROM classes")
or die(mysql_error());
echo "<table border='1' cellpadding='10'>";
echo "<tr> <th>ID</th> <th>Title</th> <th>Summary</th> <th>Content</th> <th>Category</th> </tr>";
// loop through results of database query, displaying them in the table
while ($row = mysql_fetch_array($result)) {
// echo out the contents of each row into a table
echo "<tr>";
echo '<td>' . $row['id'] . '</td>';
echo '<td>' . $row['title'] . '</td>';
echo '<td>' . $row['summary'] . '</td>';
echo '<td>' . $row['content'] . '</td>';
echo '<td>' . $row['categoryid'] . '</td>';
echo '<td><a href="editClasses.php?id=' . $row['id'] . '">Edit</a></td>';
echo '<td><a href="deleteClasses.php?id=' . $row['id'] . '">Delete</a></td>';
echo "</tr>";
}
// close table>
echo "</table>";
我真的很感激你能提供的任何帮助,这个让我已经困住了几天了!
答案 0 :(得分:1)
看看mysql JOIN功能。它只需要一个查询,而不是两个,所有值都在一个结果集中:
http://dev.mysql.com/doc/refman/5.7/en/join.html
您的查询将如下所示:
SELECT * FROM classes LEFT JOIN catclasses ON classes.categoryid=catclasses.id;