1

I'm trying to implement PDO in my web site and i was checking the use of fetch and fetchAll and found this strange behaviour. This code works perfectly:

    $query="SELECT `id`, `username`, `nome`, `email`, `pwd`, `level` FROM `users` WHERE `username`= ? LIMIT 1";
    $stmt=$myconn->prepare($query);
    $stmt->bindParam(1, $uname);
    $stmt->execute();

    $row=$stmt->fetchAll();
    print_r($row);

while this one doesn't work: fetch returns false with no error code (00000):

    $query="SELECT `id`, `username`, `nome`, `email`, `pwd`, `level` FROM `users` WHERE `username`= ? LIMIT 1";
    $stmt=$myconn->prepare($query);
    $stmt->bindParam(1, $uname);
    $stmt->execute();

    while($row = $stmt->fetch()) {
        echo $row->username . "\n";
        echo $row->nome . "\n";
        echo $row->email . "\n";
    }

Any idea why?

Tiziano Mischi
  • 176
  • 1
  • 16
  • 3
    `$row->username` -> `$row["username"]`; See: http://php.net/manual/en/pdostatement.fetch.php – Rizier123 Jan 11 '16 at 22:12
  • As @Rizier123 or `$stmt->fetch(PDO::FETCH_OBJ)` then access properties as an object. – Script47 Jan 11 '16 at 22:13
  • Oh wonderful, the guide i was following missed the FETCH_OBJ command, thanks.By the way, $row->username works. – Tiziano Mischi Jan 11 '16 at 22:17
  • @TizianoMischi you can set the default fetch type so you don't have to expressly each time say `PDO::FETCH_OBJ`. Check [this](http://stackoverflow.com/questions/3893858/is-is-possible-to-set-a-default-pdo-fetch-mode) link. – Script47 Jan 11 '16 at 22:20
  • @Script47 your comment is interestering, indeed i set `PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC` for the use of fetchAll. This means that i cannot set two different behaviour, one for fetchAll and one for fetch as default? So i have to choose which one i'll use it mainly, set the default for that one and then always specify the fetch type for the other one – Tiziano Mischi Jan 11 '16 at 22:45
  • That's correct. There's one default for both `fetch` and `fetchAll`. – Barmar Jan 11 '16 at 22:48

1 Answers1

1

This should work:

$stmt=$myconn->prepare($query);
$stmt->bindParam(1, $uname);
$stmt->execute();
$stmt->setFetchMode(PDO::FETCH_ASSOC);  
while($row = $stmt->fetch()) {
    echo $row['username'] . "\n";
    .        
    .
    .
}
Adam Tong
  • 571
  • 1
  • 4
  • 16