使用php表中的查询结果填写下拉列表

时间:2014-03-31 02:33:09

标签: php html sql

我一直在尝试使用来自mysql表的php查询结果填充下拉列表,但列表为空。有人可以看看我的代码并告诉我,我做错了什么。

我的查询是Select cat from kernel

我使用了代码:$results = $query->fetchAll();

继承我的代码:

<?php

$dbhandle = new PDO('host','username','password');


$sql = "SELECT cat FROM kernel";
$results = $query->fetchAll();

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

?>

1 个答案:

答案 0 :(得分:0)

<?php

$sth = $dbhandle->prepare("SELECT cat FROM kernel");
$sth->execute();
$results = $sth->fetchAll(PDO::FETCH_ASSOC);

echo "<select name='cat'>";
foreach($results as $row) {
    echo "<option value='" . $row['cat'] . "'>" . $row['cat'] . "</option>";
}    
echo "</select>";

?>

http://us2.php.net/manual/en/pdostatement.fetchall.php