如何在循环遍历父表中的行时检索相关的子行


How to retrieve related child rows as I loop through rows from the parent table?

在遍历外部查询的行时,我需要运行一个子查询(或其他)。我已经尽了最大的努力,但一直无法发挥作用。

这是我的while循环:

$sql = "SELECT * FROM $db ORDER BY Created DESC";
$ps = $pdo->prepare($sql);
if (!$ps) {
    echo "'nPDO::errorInfo():'n";
    print_r($dbh->errorInfo());
}else{
    $ps->execute();
    $ps->setFetchMode(PDO::FETCH_OBJ);
    while($row = $ps->fetch()) {
        echo "<tr>'n";
            echo "  <td>". $row->SARNo . "</td>'n";
            echo "  <td>". $row->Quals . "</td>'n";
            echo "  <td>". <!-- how do I insert results of $query here? --> . "</td>'n";
            echo "  <td>". $row->CAGE . "</td>'n";
            echo "  <td>". $row->Supplier_Name . "</td>'n";
            echo "  <td>". $row->Assigned_To_HEBCO . "</td>'n";
            echo "  <td>". $row->SAR_Completed . "</td>'n";
        echo "</tr>'n";
    }
}

以下是获取当前记录的关联NSN的查询:

$query = "SELECT NSN_Src.NSN FROM NSN_Src INNER JOIN (SAR2 INNER JOIN REL_SAR_NSN ON SAR2.ID = REL_SAR_NSN.SAR_ID) ON NSN_Src.ID = REL_SAR_NSN.NSN_ID WHERE (((SAR2.ID)=$uid))";

我对Access不是很熟悉,更不熟悉将Access与PHP一起使用,所以这个小项目一直很"有趣"(至少可以说),因为缺乏PHP函数(与MySQL可用的大量函数相比)。

我们非常感谢您的任何帮助,一个有效的解决方案将使您按照我的意愿获得我世俗物品的50%(这可能是一大笔债务,所以如果您愿意,您可以拒绝)。:)

正如您可能已经发现的,Access SQL没有像MySQL的GROUP_CONNCT()那样的聚合函数。因此,您需要让您的PHP代码使用第二个准备好的语句和一个内部循环来创建子项列表,如下所示:

<?php
header('Content-Type: text/html; charset=windows-1252');
?>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=windows-1252" />
<title>PDO example</title>
</head>
<body>
<?php
$connStr = 
        'odbc:' .
        'Driver={Microsoft Access Driver (*.mdb)};' .
        'Dbq=C:''Users''Public''__SO''28502544.mdb;' .
        'Uid=Admin;';
$db = new PDO($connStr);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sqlParent = "SELECT ID, ParentName FROM Parent";
$psParent = $db->prepare($sqlParent);
$sqlChild = "SELECT ChildName FROM Child WHERE ParentID = ?";
$psChild = $db->prepare($sqlChild);
$psChild->bindParam(1, $parentID, PDO::PARAM_INT);
echo '<table border=1>';
$psParent->execute();
while ($rowParent = $psParent->fetch()) {
    echo '<tr>';
    echo '<td>';
    echo $rowParent["ParentName"];
    echo '</td>';
    // collect child items into array
    $parentID = $rowParent["ID"];
    $psChild->execute();
    $childItems = array();
    while ($rowChild = $psChild->fetch()) {
        $childItems[] = $rowChild["ChildName"];
    }
    // string together and insert into table cell
    echo '<td>';
    echo implode(", ", $childItems);
    echo '</td>';
    echo '</tr>';
}
echo '</table>';
?>
</body>
</html>