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. 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. And if you want to use object notation, you have to specify PDO::FETCH_OBJ
instead of ...ASSOC
.
Anyway, PDO::FETCH_LAZY
should be most preferred way, as it will let you use ANY notation:
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.