0

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

[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;

}
4

1 回答 1

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']);
}
于 2012-10-10T14:30:46.603 回答