PDO :: Fetch & FetchAll

2

Because the following code works:

 $stmt = $pdo->prepare("SELECT * FROM dados");
 $stmt->execute();
 $codigos = $stmt->fetch();

 echo $codigos['codigo'];

So I can not use it?

   $stmt = $pdo->prepare("SELECT * FROM dados");
   $stmt->execute();
   $codigos = $stmt->fetchAll();

   echo $codigos['codigo'];
    
asked by anonymous 05.05.2015 / 13:52

3 answers

5

Good friend the difference between fetch and fetchAll is in return. In the case of fetch is a simple array, while in fetchAll is a multidimensional array, also called an array. In your situation it is working fetch because you only have one record in the bank, once you have more than one record in the bank, it will throw a PDOException because it is receiving more than one object from the bank while only supports one, unless you use LIMIT 0,1 in your query, but it will only result in a result from the database and I do not believe that is what you need. For this you would have to use fetchAll and to print on the screen would have to use foreach , would look like the code:

foreach($codigos as $item)
{
   echo $item["codigo"];
}
    
05.05.2015 / 16:08
4

fetch() returns only one row of the array, while fetchAll() returns more than one, ie this array is indexed by numbers, it takes a loop to display all the information.

To get the numeric indexes use the array_keys function:

$codigos = $stmt->fetchAll();
$keys = array_keys($codigos);

The array returned by fetchAll is in this format:

Array
(
[0] => Array
    (
        [nome] => a
        [id] => 1
    )

[1] => Array
    (
        [nome] => b
        [id] => 2
    )

[2] => Array
    (
        [nome] => c
        [id] => 3
    )
    
05.05.2015 / 13:55
1

Because the data structure is different from a look at the documentation for fetch and < a href="http://php.net/manual/pt_BR/pdostatement.fetchall.php"> fetchAll you'll see the difference. Basically get used to print_r or var_dump to see the structure of the data you're working on

    
05.05.2015 / 14:00