填充下拉列表,准备好的语句返回空

时间:2017-08-29 13:00:05

标签: php

这几个小时一直在摸不着头脑,似乎无法使用准备好的陈述将结果返回到下拉列表。

这是我的代码:

<?php
require_once 'db.php';


$stmt = $mysqli->prepare("SELECT country_id, country_name, flag_file, 
header_img, intro FROM countries WHERE country_id = ? ORDER BY country_id");
$stmt->bind_param('s', $countryRow);
$stmt->execute();
$stmt->bind_result($id, $countryName, $flag, $headerIMG, $intro);
$stmt->store_result();
$data = array();
while($row = $stmt->fetch()) {
    if(!$stmt) {
        echo "Failed to execute: (" . $stmt->errno . ")" . $stmt->error;
    }

$data[] = array(
  "name" => $countryName,
  "flag" => $flag,
  "header" => $headerIMG,
  "intro" => $intro
);

$stmt->close();
}     
?>

然后使用foreach循环下拉列表的代码:

<select type="text" name="país">
        <?php foreach ($data as $key => $value){ ?>
               <option value="<?=$value['country_id']?>"><?php echo 
               $value['country_name'] ?></option>
       <?php } ?>
</select>

首次使用数组。谢谢你的帮助。

1 个答案:

答案 0 :(得分:1)

为什么不使用您已有的while循环,而不是创建另一个$data数组:

<?php
require_once 'db.php';
$stmt = $mysqli->prepare("SELECT country_id, country_name, flag_file, 
header_img, intro FROM countries WHERE country_id = ? ORDER BY country_id");
$stmt->bind_param('s', $countryRow);
$stmt->execute();
$stmt->bind_result($id, $countryName, $flag, $headerIMG, $intro);
$stmt->store_result();
$data = array();
$option = '';
while($row = $stmt->fetch()) {
    if(!$stmt) {
        echo "Failed to execute: (" . $stmt->errno . ")" . $stmt->error;
    }
    $option .= "<option value='" . $row['country_id']. "'>" . $row['country_name']. "</option>";
    /*$data[] = array(
        "name" => $countryName,
        "flag" => $flag,
        "header" => $headerIMG,
        "intro" => $intro
    );*/
    $stmt->close();
}     
?>
<select type="text" name="país">
    <?php echo $option; ?>
</select>
相关问题