如何回显另一个 table 的值?

How to echo values from another table?

您好,我有 2 个 table 名为 tbl_guardtbl_recordstbl_guard 有列 guard_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 在循环中回显,我想要 tbl_guard table.[=22 中的 fullname =]

非常感谢您的帮助!

你想实现的好像是一个外键关系——你必须使用JOINS。在您的示例中:

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

阅读 MySQL 文档,您会经常需要它!

我已经开始工作了,这是我的 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

谢谢大家!

使用连接

$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}";
}