Search code examples
phploopsmysqlireturndo-while

How to make do-while loop works for its not looping at all?


I have these codes. I chose the do-while loop, so I can do the looping, but somehow it doesn't work.

So, in my database, there are at least 5 rows from the "SOALTXT" field, that have id=S01, which mean, tht it should do looping for 5 times. But somehow it only shows one row. Like this:

not expected output:
not expected output

<?php
    include "koneksi.php";
    $query = mysqli_query($connection,"SELECT * FROM buatsoal_db ORDER BY ID DESC");
    $result = mysqli_fetch_array($query);
    $id = $result['ID'];
    ?>

<?php
    do{ ?>
        <form method= 'post'>
        <input name='next' type='submit' id='next' value='next'>
        </form>
            <?php if(isset($_POST['next'])){ 
    >           $row = mysqli_fetch_array ($query);
                echo $row['SOALTXT'];           
            ?>
            <br>
            <br>
            <?php           
            } 
            ?>

<?php   }
    while ($id =='S01');
?>

For the output, I expect 5 'next ' button, and when it clicked, show up each one 'soaltxt'.


Solution

  • The variable $id is not being updated inside the do while loop. Just add another

    $id = $row['ID']
    

    before the echo in the loop.

    Edit:

    I was going to post a new snippet but the answer from @Omar Abbas is along the lines of what I intended. I would get the form outside of the loop and add a hidden input to pass an index to the next page so you know how many times you pressed next so you know how many rows to display.

    Learning to ask the right questions is important in this industry. Important parts of it are good phrasing and as few assumptions as possible.