在PHP循环中使用两个或多个SQL查询语句


Using two or more SQL query statements in a PHP loop

$query_country = "select abbr,full_name from Country";
$result_country = $db->query($query_country);//this is the first SQL
foreach ( $result_country as $row ){
    echo '<optgroup label="' . $row['full_name'] . '">';
    $abbr = $row['abbr'];
    $query_airport = "select location from Airport where country_abbr = $abbr ";
    $result_airport = $db_other->query($query_airport);//this is the second SQL
    foreach ( $result_airport as $row_prime ){
        echo '<option>'.$row_prime['location'].'</option>';
        }
    echo '</optgroup>';
}
如上所示,第二个SQL不起作用。

我试图在'config.php'文件中新建一个PDO变量($db_other),但它仍然不起作用。

我的问题是如何在PHP循环中使用第二个SQL。

我想这样做的原因是我需要通过'Country name'创建一个选择表组

尝试引用您的查询变量,并使用db对象$db来运行查询

$query_airport = "select location from Airport where country_abbr = '$abbr' ";
$result_airport = $db->query($query_airport);

也检查$abbr有值,所以代码看起来像:-

if(!empty($abbr)) {
   $query_airport = "select location from Airport where country_abbr = '$abbr' ";
    $result_airport = $db->query($query_airport);
    foreach ( $result_airport as $row_prime ){
        echo '<option>'.$row_prime['location'].'</option>';
        }
}