我看到这已被问过几次,但是跟随所有其他线程让我无处可去。我试图从数据库中填充下拉列表,但我不断得到一个空白下降...我发誓一定是因为我正在制造一个简单的错误。
<select name="Verb List">
<?php fillVerblist($dbc); ?>
</select>
<?php
function fillVerblist($dbc) {
mysqli_query($dbc, 'SET NAMES UTF8');
$sql = mysqli_query($dbc, "SELECT * FROM verblist WHERE form = 'F'");
while ($row = mysql_fetch_assoc($sql)){
echo' <option value="verblist">'.$row['specificColumn'].'</option>';
}
}
?>
谢谢!
答案 0 :(得分:1)
根据PHP Manual:{5.5}已弃用mysql_fetch_assoc()
,因此请使用mysqli_fetch_assoc()
如果您希望每个选项值与显示的文本相匹配,请执行以下操作:
while ($row = mysqli_fetch_assoc($sql)){
echo' <option value="'.$row['specificColumn'].'">'.$row['specificColumn'].'</option>';
}
正如DontPanic在评论中所说,你也可以省略value属性,文本将被用作值。
调试空白选择进一步将其抛入while循环:
echo '<pre>';
echo $row;
echo '</pre>';
这将告诉您从数据库返回的内容以及您的数据/查询是否不正确。
答案 1 :(得分:1)
花了一点时间写,但是像下面这样的简单类会简化整个菜单的创建 - 只需输入不同的参数,然后弹出不同的菜单。 DOMDocument
最常见的用法往往是解析文档 - 无论是XML还是HTML,但它的方法非常适合动态生成内容 - 在本例中是一个技术上简单的选择菜单在DOM中纠正。
<?php
class selectmenu{
private $dbo;
private $name;
private $sql;
public function __construct( $dbo, $name, $sql ){
$this->dbo=$dbo;
$this->name=$name;
$this->sql=$sql;
}
public function create(){
$result=$this->dbo->query( $this->sql );
if( $result ){
$dom=new DOMDocument;
$select=$dom->createElement('select');
$dom->appendChild( $select );
$attr=$dom->createAttribute( 'name' );
$attr->value=$this->name;
$select->appendChild( $attr );
while( $rs = $result->fetch_object() ){
/*
The option value is the ID and the innerHTML is
whatever column name is designated as `value` in the
query. The names of these are fairly arbitary - you
could call them anything really in the query but change
the field here( ie: $rs->value to $rs->somecolumn )
*/
$option=$dom->createElement('option');
$option->nodeValue=$rs->value;
$attr=$dom->createAttribute( 'value' );
$attr->value=$rs->id;
$option->appendChild( $attr );
$select->appendChild( $option );
}
return $dom->saveHTML();
}
return 'error';
}
}
要使用课程,你会做这样的事情。
$dbhost = 'localhost';
$dbuser = 'root';
$dbpwd = 'xxx';
$dbname = 'xxx';
$db=new mysqli( $dbhost, $dbuser, $dbpwd, $dbname );
/* the column `Name` is aliased as `value` */
$sql_city="select `id`, `Name` as 'value' from `city` limit 20;";
$name_city='city';
/* note column aliases !! */
$sql_country="select `code` as 'id', `Region` as 'value' from `country` limit 20;";
$name_country='country';
$obj=new selectmenu( $db, $name_city, $sql_city );
$city=$obj->create();
$obj=new selectmenu( $db, $name_country, $sql_country );
$country=$obj->create();
echo $city, $country;
?>
可以使用PDO完成相同的想法,但这些方法需要适当更改。
更具体地针对原始问题
$sql="SELECT `col` as 'id', `othercol` as 'value' FROM verblist WHERE form = 'F'";
$name='verblist';
$obj=new selectmenu( $dbc, $name, $sql );
$menu=$obj->create();
echo $menu;