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

Issue

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

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);
    }
?>

Answered By – Robert

Answer Checked By – Mary Flores (BugsFixing Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *