Echoing out table id trouble


Hi everyone I am trying to echo out some table id’s. I echo out a few but it always misses the first table for example id 1. This is the code I have so far [code] try{
$stmt = $dbh->prepare(‘SELECT * FROM forum’);
$row = $stmt->fetch(PDO::FETCH_ASSOC);

    if($row != 0){
        while($row = $stmt->fetch(PDO::FETCH_ASSOC))
        echo $row['id'] ."/ ";
catch (PDOException $e){
    echo $e->getMessage();
} [/code]

When this is run I get 6/ 5/ when it should be 5 6 7


add an order by to your query


Hi i’ve tried it but still no luck.


No luck on the ordering, or on the missing ID?


on the missing id. If I create another post the number appears but not the latest post I just created.


You are fetching and discarding the first row from the result set. This is a common problem when pasting code together, rather than writing it to do what you want. To find the errant fetch statement, play computer and read through your code to see what it is doing.



Investigate the documentation


Ok after read the docs I still had no clue. But i’ve managed to sort it ith the new code:

$stmt = $dbh->query(‘SELECT * FROM forum’);

        while($row = $stmt->fetch()) {
        echo $row['id'];
 catch (PDOException $e){
     echo $e->getMessage();
 }       [/php]

So far this has worked I don’t know whether this is the best way but it does what I need for now.


What [member=87768]phdr[/member] was referring to was this,

[php]$row = $stmt->fetch(PDO::FETCH_ASSOC);
was being called twice. The first time it would fetch a row, but it wasn’t used. Then, you call it again, skipping the first row.

Another way to do it, would be to fetch all the records rather than one at a time. And iterate thru that result set.