Richard
Richard

Reputation: 4546

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()->prepare($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

Upvotes: 1

Views: 2222

Answers (2)

TheCarver
TheCarver

Reputation: 19713

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'];
    }
}

Upvotes: 0

Pekka
Pekka

Reputation: 449415

If you expect only one row, use PDOStatement::fetch() instead of fetchAll().

Upvotes: 1

Related Questions