0

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?

2
  • 1
    because you don't change the $buildname variable in the while loop. Commented Jan 19, 2014 at 10:48
  • You’re printing $build_name, which gets assigned outside the while loop. Try printing $card_data_result['build_name'] instead. Commented Jan 19, 2014 at 10:48

2 Answers 2

3

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)

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

7 Comments

whell, that works but the way i'm doing it i'm geting this error: Parse error: syntax error, unexpected T_ENCAPSED_AND_WHITESPACE, expecting T_STRING or T_VARIABLE or T_NUM_STRING in C:\wamp\www\pcbuilds\index.php on line 123 and line 123 is: <h2 class=\"card-title\">$card_data_result['build_name']</h2>
PHP and html concatenation seem incorrect.. echo "<h2 class=\"card-title\">".$card_data_result['build_name']."</h2>";
that works but again is not displaying one item from the list :/
Can you check running this query "SELECT * FROM builds" in your DB directly ? Does it return 4 items ?
Showing rows 0 - 2 ( ~3 total , Query took 0.0006 sec) (i removed one so now are 3 total)
|
1

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
}

1 Comment

this will give me an error Parse error: syntax error, unexpected T_ENCAPSED_AND_WHITESPACE, expecting T_STRING or T_VARIABLE or T_NUM_STRING in C:\wamp\www\pcbuilds\index.php on line 123 and line 123 is: <h2 class=\"card-title\">$card_data_result['build_name']</h2> which is inside <?php echo "" ?>

Your Answer

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