gpt4 book ai didi

PHP MySQL 联接两个表查询

转载 作者:行者123 更新时间:2023-11-29 17:25:31 24 4
gpt4 key购买 nike

我有两个表,即抽象表和作者,具有一对多关系,对于 while 循环的每次迭代,我想显示一个 html 表,其中包含抽象表中唯一的数据行以及作者表中的相应行。

这就是我所做的:

public function getAll() {
try {
$sql = " SELECT tbl_abstract.abstract_id, tbl_abstract.first_name,
tbl_abstract.last_name,tbl_abstract.content,
tbl_author.afirst_name, tbl_author.alast_name,
tbl_author.aaffilition
FROM tbl_abstract
INNER JOIN tbl_author ON tbl_abstract.abstract_id = tbl_author.abstract_id
GROUP BY tbl_abstract.abstract_id";

$stmt= $this->pdo->prepare($sql);
$stmt->execute();
$count = $stmt ->rowCount();
while($row = $stmt->fetch(PDO::FETCH_ASSOC)){
?>

<table class="table" >
<tr>
<td align="center" >
//data from tbl_abstract
<?php echo $row["abstract_id"]; ?>. <?php print($row["abstract_title"]); ?>
<?php echo $row["first_name"].'&nbsp;'.$row["last_name"]; ?>,

//data from tbl_author
<?php echo $row["afirst_name"].'&nbsp;'.$row["alast_name"];?>
</td>
</tr>
<tr>
<td align="center" ">
//data from tbl_abstract
<?php print($row["content"]); ?>
</td>
</tr>

</table>
<?php
}
}catch(PDOException $e){
echo $e->getMessage();
return false;
}
}

tbl_author 中有 3 条记录与 tbl_abstract 中的 Abstract_id 相关联,但我只得到一条记录,而不是 3 条。请帮忙

最佳答案

试试这个:-

<?php

$sql = "SELECT *
FROM tbl_abstract
where abstract_id IN (SELECT distinct abstract_id
FROM tbl_abstract)";

$stmt= $this->pdo->prepare($sql);
$stmt->execute();
$count = $stmt ->rowCount();
?>
<table class="table" >
while($row = $stmt->fetch(PDO::FETCH_ASSOC)){
?>
<tr>
<td align="center" >
//data from tbl_abstract
<?php echo $row["abstract_id"]; ?> <?php print($row["abstract_title"]); ?>
<?php echo $row["first_name"].'&nbsp;'.$row["last_name"]; ?>,
<?php
$sql1 = "SELECT *
FROM tbl_author
WHERE abstract_id = '".$row["abstract_id"]."'" ;
$stmt1= $this->pdo->prepare($sql1);
$stmt1->execute();
while($row1 = $stmt1->fetch(PDO::FETCH_ASSOC)){
//data from tbl_author
echo $row1["afirst_name"].'&nbsp;'.$row1["alast_name"];
} ?>
</td>
<td align="center">
//data from tbl_abstract
<?php print($row["content"]); ?>
</td>
</tr>
<?php } ?>

</table>

关于PHP MySQL 联接两个表查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51003585/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com