1

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

1
  • What is $row[0]? var_dump($row[0]) Commented Feb 8, 2013 at 16:42

1 Answer 1

5

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanx! I'm wondering how to make it output as long as it gets input. Something like While ($row){ print $row[this value will increase]['naam'] . "\t";)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.