当我从父表循环遍历行时,如何检索相关的子行?

时间:2015-02-13 15:08:10

标签: php sql ms-access pdo

当我遍历外部查询的行时,我需要运行子查询(或其他东西)。我尽可能多地尝试,但一直无法让它发挥作用。

这是我的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,所以这个小项目已经很有趣了#34; (至少可以说)由于缺乏PHP功能(与MySQL可用的过多功能相比)。

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

1 个答案:

答案 0 :(得分:1)

正如您可能已经发现的那样,Access SQL没有像MySQL GROUP_CONCAT()这样的聚合函数。因此,您需要让您的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>