0

I did a while loop to display data from my table cards. The problem is that it does not display the first row of the table

$reponse = $bdd->query('SELECT * FROM cartes');
$donnees = $reponse->fetch();

while ($donnees = $reponse->fetch()) {
?>

    <p>
    <strong>Carte: </strong> <br /><br />
    <u>ID:</u> <?php echo $donnees['ID']; ?><br />
    <u>Propriétaire:</u> <?php echo $donnees['nom']; ?><br />
    </p>

    <?php
}

$reponse->closeCursor();
?>

My table:

CREATE TABLE IF NOT EXISTS `cartes` (
`ID` int(10) unsigned NOT NULL AUTO_INCREMENT,
`nom` varchar(255) NOT NULL,
PRIMARY KEY (ID)
) ENGINE=INNODB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=51;

Thanks

1
  • 3
    remove this line $donnees = $reponse->fetch(); Commented Mar 8, 2016 at 9:36

2 Answers 2

2

The "offending" line of code is the $donnees = $reponse->fetch(); as @Goudea Elalfy pointed out in the comments.

The reason for this is because that after you have fetched the data as below

$reponse = $bdd->query('SELECT * FROM cartes'); //Fetches the data

You then fetch a single row from the returned result.

$donnees = $reponse->fetch(); //Fetches the first row from the result set

And then you fetch the data again in the while loop:

while ($donnees = $reponse->fetch()) { // starts from the second row in the result set.

But because you've all ready asked the result set to return a single row from the result set once, the response returns the SECOND set of results / data in the while loop and each time you loop through the response you'll get the next set of data.

You can look at it as a array, the first time you call the result set you get $response[0] the second time you call the result set you get $response[1] and so on.

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

Comments

1
$reponse = $bdd->query('SELECT * FROM cartes');
$donnees = $reponse->fetch();

this $reponse->fetch() will fetch first row from response. so when do $reponse->fetch() in while loop it will start from second row. so you need to remove $donnees = $reponse->fetch(); outside while loop.

Comments

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.