PHP PDO Fetch row and print values

梦想与她 提交于 2020-01-30 13:14:27

问题


I couldn't understand the exact working of the fetch/fetchall in PDO.can i get a simple example for PDO fetch for fetching each row and displays its values iteratively?


回答1:


There are a lot of examples around.. You can do a simple fetch using a while loop too

<?php
//your PDO connection goes here.....
$stmt = $db->query('SELECT username FROM yourtable');

while($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
    echo $row['username'];
}

Read the PHP Manual on PDOStatement::fetch


By using a fetchAll , you can grab all the results in a single array..

$stmt = $db->query("SELECT username FROM yourtable");
$results = $stmt->fetchAll(PDO::FETCH_ASSOC);
print_r($results);

Read the PHP Manual on PDOStatement::fetchAll




回答2:


When you perform a query, you get a PDOStatement object. That object, once the query gets executed, will be populated with the results.

Now you are given two functions:

$pdoStatement->fetch();

and

$pdoStatement->fetchAll();

fetch will fetch one row at a time. It also advances automatically, so you don't need to call a next() function. Just call fetch in a loop, and you'll get all of your results. fetch returns an array.

fetchAll will fetch all of the rows at once. Returning an array of arrays (where each inner array is one row).



来源:https://stackoverflow.com/questions/23571676/php-pdo-fetch-row-and-print-values

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!