user2945758
user2945758

Reputation:

PHP while loop displays same result over and over again

I'm using a while loop in order to display items from the database but this instead is displaying the same result and ignoring one. Example: if the first items is called Item1 and I have 4 items in the database (Item1, Item2, Item3, Item4) it will display 3 times the Item1.

<?php
    $card_data =  mysqli_query($con, "SELECT * FROM builds");
    $card_data_result = mysqli_fetch_array($card_data);
    $build_name = $card_data_result['build_name']; 

while ($card_data_result = mysqli_fetch_array($card_data)){
    echo "$build_name";
    }
?>

Any ideas how to fix it?

Upvotes: 0

Views: 741

Answers (2)

RaviRokkam
RaviRokkam

Reputation: 789

Try this :

    $card_data =  mysqli_query($con, "SELECT * FROM builds");
    //$card_data_result = mysqli_fetch_array($card_data);
    //$build_name = $card_data_result['build_name']; 
    while ($card_data_result = mysqli_fetch_array($card_data)){
        echo $card_data_result['build_name']."<br />";
    }

Explanation: Following code only returns one row. To get more rows, you need a loop:

$card_data_result = mysqli_fetch_array($card_data);
$build_name = $card_data_result['build_name'];

Since you have 4 items, your while loop will print 4 times $build_name (the same item)

Upvotes: 3

Rewrite your while like this

while ($card_data_result = mysqli_fetch_array($card_data)){
echo $card_data_result['build_name']; //<---- Brought this statment inside what you had outside of the while loop
}

Upvotes: 1

Related Questions