在下拉菜单中显示特定字段的数据库条目

时间:2012-10-10 13:50:53

标签: php

目前我正在使用以下代码在下拉菜单中显示所有帐户类型:

[HTML]

<select name="sel-account-name" id="sel-account-name" class="cp-controls-sml input-select input-select-xxlrg" tabindex="6">
    <option value="0">Select Account</option>

    <?php echo $options?>

</select>

[PHP]

<?php

## Get all accounts from tblAccounts to display on add user page

mysql_connect('localhost', 'root', '');


mysql_select_db('database');

$sql="SELECT AccountName FROM tblaccounts";
$result=mysql_query($sql);

$options="";

while ($row=mysql_fetch_array($result)) {

    $id=$row["Id"];
    $accname=$row["AccountName"];
    $options.="<OPTION VALUE=\"$accname\">".$accname.'</option>';

}

?>

哪种方法完全正常...我正在尝试使用PDO编写此代码,如下所示: - 如果有人可以提供帮助,我只需要一点帮助就可以了解这一点,但似乎无法让它发挥作用。

public static function getAllAccounts() {

    $pdo = new SQL();
    $dbh = $pdo->connect(Database::$serverIP, Database::$serverPort, Database::$dbName, Database::$user, Database::$pass);

    try {

        $query = "SELECT AccountName FROM tblaccounts";


    $stmt = $dbh->prepare($query);

    $stmt->execute();

    $row = $stmt->fetch(PDO::FETCH_BOTH);

    $stmt->closeCursor();

}

catch (PDOException $pe) {
    die("Error: " .$pe->getMessage(). " Query: ".$stmt->queryString);
}

$dbh = null;

}

1 个答案:

答案 0 :(得分:1)

方法:

public static function getAllAccounts() {
    $pdo = new SQL();
    $dbh = $pdo->connect(Database::$serverIP, Database::$serverPort, Database::$dbName, Database::$user, Database::$pass);
    try {
        $query = "SELECT AccountName FROM tblaccounts";
        $stmt = $dbh->prepare($query);
        $stmt->execute();
        $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
        $stmt->closeCursor();
    } catch (PDOException $pe) {
        die("Error: " .$pe->getMessage(). " Query: ".$stmt->queryString);
    }
    $dbh = null;
    return $rows;
}

输出:

foreach(<classname>::getAllAccounts() as $acct) {
    $options.=sprintf('<option>%s</option>', $acct['AccountName']);
}