Crazy
Crazy

Reputation: 139

Php - While loop data MySQL

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

Upvotes: 0

Views: 99

Answers (2)

Epodax
Epodax

Reputation: 1828

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.

Upvotes: 2

Hiren patel
Hiren patel

Reputation: 971

$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.

Upvotes: 1

Related Questions