从数据库中提取以形成选择

时间:2014-04-04 09:07:09

标签: php html forms mysqli

处理我要从我的数据库中提取的项目,并在表单select中显示池名称。但不确定如何走得更远。

$con=mysqli_connect("localhost","root","","nih_bw");
// Check connection
if (mysqli_connect_errno($con))
  {
  echo "Failed to connect to MySQL: " . mysqli_connect_error();
  }

  $sql = "Select name from pools";

if(!$result = $db->query($sql)){
    die('There was an error running the query [' . $db->error . ']');

 }

mysqli_close($con);

3 个答案:

答案 0 :(得分:1)

您可以这样做:

<?php
$con=mysqli_connect("localhost","root","","nih_bw");
// Check connection
if (mysqli_connect_errno()){
  echo "Failed to connect to MySQL: " . mysqli_connect_error();
}

$result = mysqli_query($con,"Select name from pools");
echo "<select name='mypool'>";

$default_name = "foo_bar"; 
while($row = mysqli_fetch_array($result)){
  $opt_name = $row['name'];
  $str_selected = "";
  if($opt_name == $default_name){
      $str_selected = "selected";
  }
  echo "<option value='".$opt_name."' ".$str_selected." >" . $opt_name. "</option>";
}
echo "</select>";
mysqli_close($con);
?>

您可以在此处查看介绍性文章:http://www.w3schools.com/Php/php_mysql_select.asp

希望这有帮助。

答案 1 :(得分:0)

尝试使用您的查询:

<select name="batch">
    <option value="">Select One</option>
    <?php 
    $pd=$dbh->prepare("SELECT * FROM `pools`");
    $pd->execute();
    foreach($pd->fetchAll() as $rw) :
    ?>
        <option value="<?php echo $rw['id'];?>"><?php echo $rt['name'];?></option>
    <?php endforeach; ?>
</select>

它在pdo中,但你会得到我的逻辑。

答案 2 :(得分:0)

我认为这对你有用。 (代码未经过测试)

<?php
    $record = array();
    $con=mysqli_connect("localhost","root","","nih_bw");
    // Check connection
    if (mysqli_connect_errno($con)){
        echo "Failed to connect to MySQL: " . mysqli_connect_error();
    }
    $sql = "Select name from pools";
    if(!$result = mysql_query($sql,$con)){
        die('There was an error running the query [' . $db->error . ']');
    }
    else{
        while($row = mysql_fetch_assoc($result)){
            $record[] = $row;
        }
    }

    mysqli_close($con);
?>
<select>
    <?php
        foreach($record as $value){
            echo "<option>".$value."</option>";
        }
    ?>
</select>