ds2010630
2017-07-18 03:48
浏览 41
已采纳

在PHP中从sql数据库创建下拉列表

*The condition for "die" had been left out of my code by mistake when I copied it to the question. I put it back in.

I know this question might seem repetitive, but I have not found an answer in any of the other questions. I am trying to create a drop-down list based off a column in a database. I have tried two different ways and neither gave me correct results. Does anyone know a correct way of doing this?

The first way I saw in other StackOverflow answers (Fetching data from MySQL database to html drop-down list, Fetching data from MySQL database to html dropdown list). My code is below:

<?php
 $connect = mysql_connect('localhost', 'root');
 if ($connect == false)
   {
     die  ("Unable to connect to database<br>");
  }

$select = mysql_select_db('ViviansVacations');
if ($select == false)
   {
    die ("Unable to select database<br>");
  }
$query = "SELECT * FROM Destinations";
$result = mysql_query($query);
 ?>
 <select name="select1">
 <?php


while ($row = mysql_fetch_array($result))
{
echo "<option value='". $row['Europe'] ."'>" .$row['Europe'] ."</option>" ;
}
?>
</select>  

NetBeans sends me an error saying that "Text not allowed in element 'select' in this context".

The second way I tried:

<?php 
 $connect = mysql_connect('localhost', 'root'); 
  { 
   die  ("Unable to connect to database<br>");
  }
  $select = mysql_select_db('ViviansVacations'); 
  {
   die ("Unable to select database<br>");
  }
  $query = "SELECT * FROM Destinations";
  $result = mysql_query($query);
?>
<select name="select1">
<?php
  while ($line = mysql_fetch_array($result))
  {
?>
 <option value="<?php echo $line['Europe'];?>"> <?php echo 
 $line['field'];?> </option>
<?php
  }
?>
</select> 

This code did not produce any errors. However, inside the form were the opening php lines followed by an empty drop down box:

"); } $select = mysql_select_db('ViviansVacations'); { die ("Unable to select database "); } $query = "SELECT * FROM Destinations"; $result = mysql_query($query); ?>

  • 写回答
  • 好问题 提建议
  • 追加酬金
  • 关注问题
  • 邀请回答

5条回答 默认 最新

相关推荐 更多相似问题