PHP Use While instead of fetchAll
PHP Use While instead of fetchAll
PDOStatement::fetchAll()
returns an array that consists of all the rows returned by the query. From this fact we can make two conclusions:
This function should not be used, if many rows has been selected. In such a case conventional while loop ave to be used, fetching rows one by one instead of getting them all into array at once. "Many" means more than it is suitable to be shown on the average web page.
This function is mostly useful in a modern web application that never outputs data right away during fetching, but rather passes it to template.
$host = "localhost";
$db = "real_estate_source";
$user = "root";
$pwd = "123456abc";
$charset = "utf8";
$dsn = "mysql:host=$host;dbname=$db;charset=$charset";
try {
$pdo = new PDO($dsn, $user, $pwd);
$sql = "select * from users";
$stmt = $pdo->prepare($sql);
$stmt->execute();
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
echo $row["name"] . "\n" ;
}
} catch (PDOException $e) {
print "Error! " . $e->getMessage() . "<br>";
}