MYSQL PHP 使用查询结果在 foreach 循环中重新查询(复杂 - 我认为)

MYSQL PHP Use results of query to requery in foreach loop (complicated - I think)

这是我想要做的:我正在制作一个列表制作应用程序,我有 2 个 MYSQL 数据库,其中一个 table 包含每个列表的信息,例如名称,然后是第二个数据库包含 dividual tables 中的列表,列表项是那些 tables 中的行。我想从第一个(查找)table 中获取 select 所有列表并回显一些信息,然后从相应的 table 中获取所有相应的列表项。我想用第一个 table 中的标题回显 div,然后使用那个 table 也对项目进行第二个查询。是否可以为返回的每一行执行一个 foreach 循环?

到目前为止,这是我的代码:

$mysqli2 = new mysqli("localhost", "****", "****", "full_lists");
if ($mysqli2->connect_errno) {
echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " .$mysqli->connect_error;
}

$mysqli = new mysqli("localhost", "****", "****", "lists");
if ($mysqli->connect_errno) {
echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
}

if (!($stmt = $mysqli->prepare("SELECT listname, dbname FROM lists"))) {
echo "Prepare failed: (" . $mysqli->errno . ") " . $mysqli->error;
}

if (!$stmt->execute()) {
echo "Execute failed: (" . $stmt->errno . ") " . $stmt->error;
}   

$stmt->bind_result($list, $dbname);

//First statement gets the name of another table in a different database

while ($stmt->fetch()) {
$stmt2 = $mysqli2->prepare("SELECT listitems FROM {$dbname}");
//Second statement uses first to run another select statement getting
//table rows
    $stmt2->execute();
    $stmt2->bind_result($item);
    while ($stmt2->fetch()) { //replace with foreach loop?
????

    }
    }

这是我卡住的地方,我想为第一个 select 语句中的每个 $list 回显一个 div,然后使用返回的 $dbname 发出第二个语句。在每个 $div 中,我想将相应的行项目放在一个列表中。我可以做一个 foreach 循环来代替 while 循环来得到 foreach 结果吗?

编辑:这里是 tables 的图片,在不同的数据库但相同的服务器上 示例 table 每个列表的信息 table: i.stack.imgur.com/7kEOn.jpg 示例列表项 table: http://i.stack.imgur.com/XrzoD.png 感谢您的帮助

在这些情况下使用 while 循环并没有错,根据你所说的,你可以试试这个:

while ($stmt->fetch()) {
    $stmt2 = $mysqli2->prepare("SELECT listitems FROM {$dbname}");

    $stmt2->execute();
    $stmt2->bind_result($item);

    echo '<div>';
    echo '<ol>';

    while ($stmt2->fetch()) {
        echo '<li>' . $item . '</li>';
    }

    echo '</ol>';
    echo '</div>';
}