Echoing out table id trouble


#1

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’);
$stmt->execute();
$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


#2

add an order by to your query


#3

Hi i’ve tried it but still no luck.


#4

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


#5

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


#6

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.


#7

^^^

Investigate the documentation


#8

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

[php]try{
$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.


#9

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

[php]$row = $stmt->fetch(PDO::FETCH_ASSOC);
[/php]
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.