Reputation: 5612
At the moment I am using the following code to display all the Account types in a drop down menu:
[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>';
}
?>
Which works perfectly fine... I'm trying to write this using PDO as follows:- I just need a little help writing this if anybody could help as I have tried but can't seem to get it to work.
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;
}
Upvotes: 0
Views: 492
Reputation: 6818
Method:
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;
}
Output:
foreach(<classname>::getAllAccounts() as $acct) {
$options.=sprintf('<option>%s</option>', $acct['AccountName']);
}
Upvotes: 1