1

How to use multiple time PHP PDO return object?

As per my below code $result object does not display any data in while loop.

My code

try {
    $dbhandle = new PDO("sqlite:".$database);
} catch (PDOException $e) {
    echo 'Connection failed: ' . $e->getMessage();
}

$result=$dbhandle->query("select * from table");

if($result)
{
    $row=$result->fetch(PDO::FETCH_ASSOC)

    if(count($row)>0)
    {
        while ($rs1 = $result->fetch(PDO::FETCH_ASSOC, PDO::FETCH_ORI_NEXT)) 
        {
            echo "<pre>";
            print_r($rs1);
            echo "</pre>";
        }
    }
    else
    {
        // error message
    }
}
PeeHaa
  • 71,436
  • 58
  • 190
  • 262
Hkachhia
  • 4,463
  • 6
  • 41
  • 76

2 Answers2

2

This is because the cursor is at the end. So you have to reset the cursor.

http://us.php.net/manual/en/pdostatement.closecursor.php

Normally in MySQL you can use MySQL Free result.

pdo free result

Community
  • 1
  • 1
René Höhle
  • 26,716
  • 22
  • 73
  • 82
  • 1
    Please give me some suggestion or example about closecursor, i am not getting. – Hkachhia Aug 28 '12 at 12:23
  • Close cursor does not seem to reset the cursor to the beginning, allowing more fetch statements. A fetchAll followed by a closeCursor and another fetch returns an empty row. – David Grenier Sep 16 '12 at 22:36
2

Although not strictly answering your question, why dont you take a look at the $stmt->fetchAll with PDO statements which takes care of the loop for you and returns you the full associative arrays? Saves you a ton of time!

Zevi Sternlicht
  • 5,399
  • 19
  • 31