1

I can't achieve to echo the associative values from my array.

This is my PHP code:

<?php
    $servername = "my host name";
    $username = "my username";
    $password = "my password";
    $database = "my database";
    try {
        $conn = new PDO("mysql:host=$servername;dbname=$database", $username, $password);
        $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        $stmt = $conn->prepare("SELECT Street, Number, City, Country FROM extralocal");
        $stmt->execute();
    } catch (PDOException $e) {
        echo $sql . "<br>" . $e->getMessage();
    }
    $conn = null;
?>
<?php
    $places = array();
    while ($place = $stmt->fetchAll(PDO::FETCH_ASSOC)) {
        $places[] = $place;
    }
    foreach ($places as $place) {
        echo $places['Street'];
        echo $places['Number'];
        echo $places['City'];
        echo $places['Country'];

    } 
?>

For some reason when I echo each value from the array in the foreach loop nothing shows up on the loaded page, not even errors. However, if I var_dump the array I can see that the values are there, so I assume that the DB connection worked fine and the values are obtained correctly. It's just that I can't echo the specific values.

Any help will be very appreciated. Thanks in advance!

8
  • replace $places['Street']; by $place['Street']; Commented May 14, 2016 at 11:16
  • @Poria, Nothing, same result. No errors. Commented May 14, 2016 at 11:18
  • 4
    You want to use fetch and not fetchAll in your while loop. Otherwise you will store all results in one subArray! Commented May 14, 2016 at 11:20
  • @Poria, actually your suggestion also was right, as using $places instead of $place was incorrect. Thanks again. Commented May 14, 2016 at 11:24
  • @Rizier123, I don't know how to vote for both answers as they both where correct, or I just leave it like this? Commented May 14, 2016 at 11:38

1 Answer 1

2
foreach ($places as $place) {
    echo $places['Street'];
    echo $places['Number'];
    echo $places['City'];
    echo $places['Country'];
}

replace by

foreach ($places as $place) {
    echo $place['Street'];
    echo $place['Number'];
    echo $place['City'];
    echo $place['Country'];

} 

Use fetch instead of fetchAll in your while loop Hope it solves your problem

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

2 Comments

Thanks for the feedback but unfortunately it didn't work :(
Ok, after I fixed the problem as @Rizier123 suggested in the comments I also found out that this was another problem in my code. Thank you!

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.