简体   繁体   English

PHP PDO提取不起作用?

[英]PHP PDO Fetch not working?

I can successfully select an object, but I cannot fetch all rows from the database using the following code, can anyone see any obvious errors? 我可以成功选择一个对象,但是无法使用以下代码从数据库中获取所有行,有人可以看到任何明显的错误吗?

    $sql2 = "SELECT ID, Latitude, Longitude, Name FROM Countries";
    $stmt2 = $pdo->prepare($sql2);
    $stmt2->execute();

    while ($row = $stmt2->fetch(PDO::FETCH_ASSOC)) {
        echo $countryID = $row->ID;
        echo $countryName= $row->Name;
        echo $longitude2 = $row->Longitude;
        echo $latitude2 = $row->Latitude;
    }

The parameter PDO::FETCH_ASSOC tells PDO to return the result as an associative array. 参数PDO :: FETCH_ASSOC告诉PDO将结果作为关联数组返回。 SO you can fetch array not object 所以你可以获取数组不是对象

 while ($row = $stmt2->fetch(PDO::FETCH_ASSOC)) {
        echo $countryID = $row['ID'];
        echo $countryName= $row['Name'];
         //Rest of the code

    }

You have to realize that PDO::FETCH constants are on purpose. 您必须意识到PDO::FETCH常数是有目的的。 And if you want to use object notation, you have to specify PDO::FETCH_OBJ instead of ...ASSOC . 而且,如果要使用对象符号,则必须指定PDO::FETCH_OBJ而不是...ASSOC

Anyway, PDO::FETCH_LAZY should be most preferred way, as it will let you use ANY notation: 无论如何, PDO::FETCH_LAZY应该是最优选的方式,因为它将允许您使用ANY表示法:

while ($row = $stmt2->fetch(PDO::FETCH_LAZY)) {
    echo $row->ID;    // all
    echo $row['ID'];  // three
    echo $row[0];     // works
}

with even less memory overhead than any other method. 比其他任何方法都更少的内存开销。 With no memory overhead at all, to be exact. 确切地说,完全没有内存开销。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM