如何回显另一个表中的值?

时间:2015-03-22 12:31:23

标签: php mysql pdo

您好我有2个名为tbl_guardtbl_records的表。 tbl_guardguard_idfullname,而tbl_records也有guard_id。这是我的代码:

$query = "SELECT * FROM tbl_records";
$stmt = $dbc->prepare($query);
$stmt->execute();

while($row=$stmt->fetch(PDO::FETCH_ASSOC)) {
    extract($row);
    echo "<table>";
    echo "<tr>";
    echo "<td>Name</td>";
    echo "</tr>";
    echo "<tr>";
    echo "{$guard_id}";
    echo "</tr>";
}
echo "</table>";

我想做的不是在循环中回显guard_id,而是想要fullname表中的tbl_guard

非常感谢您的帮助!

3 个答案:

答案 0 :(得分:1)

您想要实现的似乎是外键关系 - 您必须使用JOINS。在您的示例中:

SELECT r.*, g.fullname FROM tbl_records r LEFT JOIN tbl_guard g ON r.`guard_id`=g.`guard_id`

阅读MySQL文档,您将更频繁地需要它!

答案 1 :(得分:1)

使用JOIN

$query = "SELECT tbl_records.*, tbl_guard.fullname FROM tbl_records LEFT 
JOIN tbl_guard ON tbl_guard.guard_id = tbl_records.guard_id"; 

在PHP中

while($row=$stmt->fetch(PDO::FETCH_ASSOC)) {
.
.
.
 echo "{$fullname}";
}

答案 2 :(得分:0)

我已经开始工作,这是我的SQL查询:

SELECT tbl_records.*, tbl_residents.fname, tbl_residents.lname FROM tbl_records LEFT JOIN tbl_residents ON tbl_residents.stud_id = tbl_records.stud_id

谢谢大家!