PHP - PDO echo $ array [' name'];不管用

时间:2016-05-14 11:15:45

标签: php mysql arrays pdo echo

我无法实现从数组中回显关联值。

这是我的PHP代码:

<?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'];

    } 
?>

出于某种原因,当echo来自array循环中的foreach的每个值时,在加载的页面上都没有显示任何内容,甚至没有错误。但是,如果我var_dump array我可以看到值存在,那么我假设数据库连接工作正常,并且正确获取值。只是我无法回应具体的价值观。

任何帮助将非常感谢。 提前谢谢!

1 个答案:

答案 0 :(得分:3)

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

替换为

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

} 

在while循环中使用fetch代替fetchAll 希望它能解决你的问题