howto get php PDO QUERY resultset in single array instead off nested in one
I needed to change a query into a JOIN of two tables.
$q = "SELECT * FROM table1 AS a JOIN table2 AS b USING(id) WHERE a.id= $id";
$stmt = db::getInstance()->prep开发者_运维知识库are($sql);
return $stmt->fetchAll(PDO::FETCH_ASSOC);
All off the sudden I cannot refer to each row value with $rows['value']
,BUT I need to use $rows[0]['value']
.
How can I avoid this behavior and get the values in the row without using [0]?
Thanks, Richard
If you expect only one row, use PDOStatement::fetch()
instead of fetchAll()
.
I use the following for returning one row:
$SQL = "SELECT myColumn FROM myTable";
$STH = $DBH->prepare($SQL);
$STH->execute();
$row = $STH->fetch();
if ($STH->rowCount > 0) {
$myColumn = $row['myColumn'];
}
And I use this for returning multiple rows:
$SQL = "SELECT myColumn FROM myTable";
$STH = $DBH->prepare($SQL);
$STH->execute();
$STH->setFetchMode(PDO::FETCH_ASSOC);
if ($STH->rowCount() > 0) {
while ($row = $STH->fetch()) {
$myColumn = $row['myColumn'];
}
}
精彩评论