如何使用 mysql 表中的数据创建下拉列表


How to make a dropdown with data from a mysql table?

我想通过从mysql表中获取值来创建一个下拉区域。此代码似乎不起作用;它打印出来的只是没有内容的下拉列表框,我怎样才能让它工作?还是有替代程序这样做?

<?
$connection = mysql_connect("localhost", "root", "");
mysql_select_db("test", $connection);
$query = "SELECT full_name FROM test";
$names = mysql_query($query);
function dropDown($content, $result)
 {
while($row = mysql_fetch_row($result))
    {
        $name = $row[0];
        $content .= "<option value='$name'>$name</option>";
    }
 }
$content=<<<EOT
           <html>
              <body>
                 <select name="name">
EOT;
dropDown($content, $names)
$content.=<<<EOT
                 </select>
              </body>   
            </html>          

EOT;
echo $content;
?>

return字符串。PHP 不是 C,你使用参数只是因为它们有时很方便。

function dropDown($result, $fieldName)
{
    $content = '';
    while($row = mysql_fetch_row($result)) {
        $name = $row[0];
        $content .= "<option value='$name'>$name</option>";
    }
    return '<select name="'.$fieldName.'">'.$content.'</select>';
}
$content = '<html><body>';
$content .= dropDown($names, 'name');
    here database details      
  mysql_connect('hostname', 'username', 'password');
mysql_select_db('database-name');
     $sql = "SELECT username FROM userregistraton";
        $result = mysql_query($sql);
         echo "<select name='username'>";
  while ($row = mysql_fetch_array($result)) {
   echo "<option value='" . $row['username'] ."'>" . $row['username'] ."</option>";}
   echo "</select>";

      here username is the column of my table(userregistration)
     it works perfectly
or simply the code is 
        <?
         $sql = "SELECT * FROM userregistraton ";
             $result = mysql_query($sql); ?>

 <select name="username" id="username">
<option value="">Select user</option>
    <?php
        while ($row = mysql_fetch_array($result))
        { ?>
          <option value="<?php echo $row['uid']?>"         <?php    if($row['uid']==$_POST["username"]) echo "selected"; ?> >
   <?php echo $row['username'];?></option>
   <?php
         } ?>

<?php echo $form->dropDownList($model,'courseprefer', array(
'(*value in database table*'=>'displaying value',
 )); ?>

您可以手动添加它们,只需确保数组中的第一个值在数据库表中即可。 :)

避免出错!