-1

I have a simple table called people with three fields. Eventually I'd like to use the results of a SELECT query to populate the default values of a form, but for now I'm just trying to echo the results of the query. I've tried lots of things and now I'm getting an 'array to string conversion' error on line 11 (the echo). Here's what I'm trying:

<?php
 include 'connect_db.php';
 $stmt = $conn->query("SELECT * FROM people");
 $results = $stmt->fetchAll(PDO::FETCH_ASSOC);
 foreach ($results as $key => $value) {
  echo $key . ':' . $value . '<br>';
 }  
?>

What am I doing wrong?

9
  • You're iterating rows, where $key is just index number and $value is an array representing database row. You can't echo array like that. Commented Jul 3, 2018 at 3:01
  • Nest another foreach on $value. Commented Jul 3, 2018 at 3:08
  • use print_r($value) in side foreach loop. then you can understand how that array . Commented Jul 3, 2018 at 3:16
  • OK, that clarifies things a little. I get: Array ( [first_name] => Bob [last_name] => Smith [name_id] => 2 ) 1 . (An aside--what is the 1 at the end?) But I'm still not clear on what to do about it. Do I need to specifically refer to each column by name? Commented Jul 3, 2018 at 3:22
  • Possible duplicate of PDO FetchAll Array Commented Jul 3, 2018 at 3:31

2 Answers 2

1

You will get back an associative array for each row. The keys will be the column names.

 include 'connect_db.php';
 $stmt = $conn->query("SELECT * FROM people");
 $results = $stmt->fetchAll(PDO::FETCH_ASSOC);
 foreach ($results as $row) {
  echo $row['some_column_name'] . '<br>';
 }  

Or

 include 'connect_db.php';
 $stmt = $conn->query("SELECT * FROM people");
 $results = $stmt->fetchAll(PDO::FETCH_ASSOC);
 foreach ($results as $row) {
    foreach ($row as $key => $value){
       echo $key . ', ' . $value . '<br>';
    }
 }  
Sign up to request clarification or add additional context in comments.

2 Comments

Does that mean I need to repeat echo $row['some_column_name'] . '<br>'; for each column?
just updated answer. But yes, you need to access each column either explicitly or by looping again over the individual row.
-1

Your problem is clear, you cannot display an array, which means you can try to use json_encode($value)

or

you can use print_r($value) not echo

2 Comments

That's the proximate problem, but the actual problem is that the wrong thing is being iterated over.
yes, and with that we can see what happen with the $value, soo he can use the correct one, or can you show me the other way?

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.