简体   繁体   English

使用HTML的FOREACH中的FOREACH

[英]FOREACH inside a FOREACH using HTML

Right now I have this page where I use foreach to fill the page. 现在,我有此页面,我在其中使用foreach来填充页面。 I then have foreach inside of that to get another table with rows on the specific ID. 然后,我在里面有foreach来获取另一个带有特定ID行的表。 The problem being anything under the nested foreach doesn't fill. 问题是嵌套的foreach下的任何内容都无法填充。

Table

在此处输入图片说明

Example: 例:

<!-- Get The Person. Results in ONE person. -->
<?
$list = $db2->prepare(" SELECT * FROM Table WHERE ID = ? ");
$list->execute(array($id));
$data = $list->fetchAll();
foreach ($data as $row) :?>

<div><?=$row["name"]?></div>

<!-- Get The Colors. Gets as many results as there are for that ID. -->
<?
$list2 = $db2->prepare(" SELECT * FROM AnotherTable WHERE ID = ? ");
$list2->execute(array($id));
$data2 = $list2->fetchAll();
foreach ($data2 as $row2) :?>

<div><?=$row2["color"]?></div>

<?endforeach?>

<!-- Doesn't show up on the page. -->
<div><?=$row["food"]?></div>

<?endforeach?>

I think you are using the same $id on both tables which is what is causing the problem. 我认为您在两个表上使用的是相同的$ id,这就是导致问题的原因。 If it is a child table and Table_ID is the foreign key, maybe 如果它是一个子表,并且Table_ID是外键,也许

" SELECT * FROM AnotherTable WHERE Table_ID = ? "

or you could use join and do 或者你可以使用加入并做

"SELECT * FROM Table INNER JOIN AnotherTable ON Table.ID = AnotherTable.Table_ID WHERE ID = ? "

Am assuming Table_ID is your foreign key there. 假设Table_ID是您的外键。

As suggested in comment, 如评论中所建议,

You should use JOIN in your query to avoid two foreach loop and get result in single query. 您应该在查询中使用JOIN以避免两个foreach循环并在单个查询中获得结果。

Write your query as below, 如下编写查询,

SELECT * FROM Table1 JOIN Table2 USING (ID) WHERE ID = ?;

same as 如同

SELECT * FROM Table1 JOIN Table2 ON Table1.ID = Table2.ID WHERE Table1.ID = ?

Note:- To differentiate column names, you can use alias in column name. 注意:-要区分列名,可以在列名中使用别名

Hope it will help you :-) 希望它能对您有所帮助:-)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM