''fetch' in PDO gets only one result [duplicate]

I have this code:

$sql = new PDO('mysql:host=localhost;dbname=b', 'root', 'root');
$f = $sql->query('select * from user');
$sql->setFetchMode(PDO::FETCH_ASSOC);

while($row = $f->fetch()){
     print_r($row);
}

The output is

Array
(
    [id] => 1
    [name] => turki
    [mail] => ablaf
    [pass] => 144
)
Array
(
    [id] => 2
    [name] => wrfwer
    [mail] => fwerf
    [pass] => werf
)

And that's what I really want. But if I do this

<?php
    $sql = new PDO('mysql:host=localhost;dbname=b', 'root', 'root');
    $f = $sql->query('select * from user');
    $f->setFetchMode(PDO::FETCH_ASSOC);
    print_r($f->fetch());
?>

The output is

Array
(
    [id] => 1
    [name] => turki
    [mail] => ablaf
    [pass] => 144
)

It has one result, but I have two rows in the table; why is that?



Solution 1:[1]

Fetch should be used to display the next row from the database result.

To get all rows, you should use fetchAll();

Change your example to:

<?php
    $sql = new PDO('mysql:host=localhost;dbname=b', 'root', 'root');
    $f = $sql->query('select * from user');
    $f->setFetchMode(PDO::FETCH_ASSOC);
    print_r($f->fetchAll());
?>

or if you want use PDOStatement::fetch to

<?php
    $sql = new PDO('mysql:host=localhost;dbname=b', 'root', 'root');
    $sth = $sql->query('select * from user');
    while($row = $sth->fetch(PDO::FETCH_ASSOC))
    {
      print_r($row);
    }
?>

Solution 2:[2]

In that case use fetchAll.

$result = $f->fetchAll();
print_r($result);

Solution 3:[3]

PDOStatement::fetch only retrieves one record from a PDOStatement object (wherever its pointer is) which is why you have to loop through fetch.

Solution 4:[4]

The fetch() method only returns a single record and sets the internal pointer to point to the next record. You are expecting from this method what it cannot return.

Perhaps try a different method like fetchAll:

<?php
    $sth = $dbh->prepare("SELECT name, colour FROM fruit");
    $sth->execute();

    /* Fetch all of the remaining rows in the result set */
    print("Fetch all of the remaining rows in the result set:\n");
    $result = $sth->fetchAll();
    print_r($result);
?>

Solution 5:[5]

$f->fetch() moves the internal result pointer to the next value (if it exists). That’s why you get all the values when you call it in while();.

Solution 6:[6]

$f->fetch() - Will get one row

$f->fetchAll() - Will get all rows

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 Rikesh
Solution 3 Peter Mortensen
Solution 4 Peter Mortensen
Solution 5 Peter Mortensen
Solution 6 Peter Mortensen