简体   繁体   中英

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?

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)

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
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM