Reputation: 1023
I'm trying PDO for database connection. somehow I get this error.. or notice but I dont know why, and it doesnt output the name...
Notice: Array to string conversion in (location) on line 31, which is
(print $row[0] . "\t";)
I dont know why?
Full code:
$query = "SELECT naam FROM paginas";
try
{
$stmt = $db->prepare($query);
$result = $stmt->execute();
}
catch(PDOException $ex)
{
die("Failed to run query: " . $ex->getMessage());
}
$row = $stmt->fetchALL();
print $row[0] . "\t";
Greetings, Merijn
Upvotes: 1
Views: 3557
Reputation: 158020
PDO::fetchAll()
returns an array of records, where the type of a record depends on the fetch style you are using.
Since you are using the default fetch style of PDO which is PDO::FETCH_BOTH
PDO::fetchAll()
will return an array of arrays. In your case it will look like:
array(2) {
[0] =>
array(2) {
[0] =>
string(3) "foo"
'naam' =>
string(3) "foo"
}
[1] =>
array(2) {
[0] =>
string(3) "bar"
'naam' =>
string(3) "bar"
}
...
}
So $row[0] is an array. You will have to address an index of it. As you see in the example array I've posted above you could use:
print $row[0]['naam'] . "\t";
or
print $row[0][0] . "\t";
Update: If you want to loop through the records instead of fetching them all at once, then use PDOStatement::fetch()
. Like this:
while($row = $stmt->fetch()) {
print $row['naam'] . "\t";
}
Note that $row
now is one dimensional array. This might be what you want.
Upvotes: 5