从数据库中检索类别名称

时间:2013-11-06 14:41:00

标签: php mysql

我的数据库中有两个表。一个名为jokes,另一个名为category

jokes

CREATE TABLE `jokes` (
  `joke_id` int(11) NOT NULL AUTO_INCREMENT,
  `joke` varchar(1024) NOT NULL,
  `category_id` int(11) NOT NULL,
  PRIMARY KEY (`joke_id`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=9 ;

category

CREATE TABLE `category` (
  `category_id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(51) NOT NULL,
  PRIMARY KEY (`category_id`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=4 ;

我的PHP在表格中显示笑话

<?php
include 'database.php';
$pdo = Database::connect();
$sql = 'SELECT * FROM jokes ORDER BY joke_id DESC';
foreach ($pdo->query($sql) as $row) {
    echo '';
    echo '<table class="table">';
    echo '<thead>';
    echo '<tr>';
    echo '<h3><th>Category Name</th></h3>';
    echo '<h3><th>Action</th></h3>';
    echo '<tbody>';
    echo '<tr>';
    echo '<thead>';
    echo '<tbody>';
    echo '<tr>';
    echo '<td >' . $row['joke'] . '</td>';
    echo '<td width=250>';
    echo '<a class="btn-big white" href="read.php?id=' . $row['joke_id'] . '">Read</a>';
    echo '&nbsp;';
    echo '<a class="btn-big green" href="update.php?id=' . $row['joke_id'] . '">Update</a>';
    echo '&nbsp;';
    echo '<a class="btn-big red" href="delete.php?id=' . $row['joke_id'] . '">Delete</a>';
    echo '</td>';
    echo '</tr>';

}
Database::disconnect();
?>

我的问题是如何通过PHP在echo category_name中显示笑话的'<h3><th>Category name</th></h3>';?因为目前,该表只显示一个笑话,没有笑话的类别名称。例如:Celebrity Joke:这是一个名人笑话。

2 个答案:

答案 0 :(得分:1)

您应该更改查询以包含类别名称。

SELECT j.joke AS joke, j.joke_id AS joke_id, c.name AS category 
FROM jokes j, category c 
WHERE j.category_id = c.category_id

之后,您可以致电$row['category']

来获取该类别

答案 1 :(得分:0)

使用此查询:

$sql = 'SELECT j.*, c.name 
        FROM jokes j 
         LEFT JOIN category c ON c.category_id = j.category_id 
         ORDER BY joke_id DESC';

要回显类别名称,请使用:$row['name']