4

I have a while loop after a PDO statement. My code is below.

 $query = "SELECT * FROM private_messages WHERE to_id = :my_id AND to_email = :email AND    recipient_delete='0' ORDER BY time_sent DESC";
 $stmt = $dbo->prepare($query);
 $stmt->execute(array(":my_id" => $my_id, ":email" => $email));
 $row = $stmt->fetch();
 while($row = $stmt->fetch()){ ...

The outputted results are always missing one of the rows, and so the most recent private message received by the user never shows. I have a notifier which tells the user how many new messages they have, which is counting correctly (it shows that they have one more message than the actual message list outputs). I cannot find the answer using Google and it is driving me crazy. This is my first ever try at programming in any kind of language since the early days of BASIC in the 80s so I am spending all of my time reading up about things, but cannot find anything to help me with this issue. Can anyone tell me where I am going wrong please? Thanks!

4
  • if you var_dump($row) it's ok ? Maybe you have some statements below ... Commented Aug 18, 2012 at 0:24
  • 1
    Please try to have a focused question title. "This is my first php programming experience" does not help others. "PHP while loop using PDO" is much better. Commented Aug 18, 2012 at 0:25
  • As @Raidenace points out you should remove that line, because when you enter the while loop that will overwrite the first result Commented Aug 18, 2012 at 0:26
  • Also note that PDOStatement implements Traversable, so you can use foreach ($stmt as $row) { ... } It's just prettier. Commented Aug 18, 2012 at 0:27

1 Answer 1

6

Remove the line:

$row = $stmt->fetch();

It puts the first line inside $row

Then when you do:

while($row = $stmt->fetch()){ ...

Its starts fetching from the second line onwards, and the first line you fetched gets lost which is why you are always missing only one line.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for the info, that works (and makes sense)..how can I +1 your reputation?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.