Logixor Logixor - 6 months ago 14
SQL Question

PHP - PDO echo $array['name']; is not working

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!

Answer
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

Comments