Reputation: 20872
I have the following PHP PDO code:
$sql='SELECT a,b,c FROM my_table WHERE d=?;';
$pds=$database->pdo->prepare($sql); $pds->execute(array($d_value)); $row=$pds->fetch();
echo $row['a'];
this works fine.
I wanted to know how I could break all 3 return values in the fetch() into variables in one line. I have tried this unsuccessfully:
$sql='SELECT a,b,c FROM my_table WHERE d=?;';
$pds=$database->pdo->prepare($sql); $pds->execute(array($d_value)); $row=$pds->fetch();
list($a,$b,$c) = $row[0];
echo $a
how do I get the 'list($a,$b,$c) = $row[0];' line to work?
thankyou very much :)
Upvotes: 0
Views: 947
Reputation: 36
$stmt->fetch()
doesn't work for me, because it returns an associative array with keys
equal to the column names
My solution to get the values from an associative array first:
list($a, $b, $c) = array_values($stmt->fetch());
Upvotes: -1
Reputation: 157828
Set PDO::ATTR_DEFAULT_FETCH_MODE to PDO::FETCH_ASSOC first, and then
$sql = 'SELECT a,b,c FROM my_table WHERE d=?';
$pds = $database->pdo->prepare($sql);
$pds->execute(array($d_value));
if ($row = $pds->fetch()) {
extract($row);
}
echo $a;
Upvotes: 0
Reputation: 945
Does this work:
list($a,$b,$c) = $row;
With $stmt->fetch() only return one row. no need to reference $row[0]
Upvotes: 2