简体   繁体   中英

PHP and Mysql while loop

I have a mysql table with orders. I am trying to loop through the orders table and select individual client orders according to their user id and display the orders on their client accounts. However, my code below just prints the first row and repeats it endlessly jaming my browser every time.

what is wrong with this and how to i solve it

<?php
$records = $conn->prepare('SELECT * FROM orders WHERE user_id= :id');
 $records-> bindParam(':id', $_SESSION['user_id']);
 $records->execute();
 $results=$records->fetch(PDO::FETCH_ASSOC);

 $i=0;
    while($i<=$results):    

        $i++;
 ?> 
<h3>Your Orders</h3>
<table >
    <tr >
        <th>Order Number</th><th>Academic Level</th><th>Order Details</th>Manage Order</th>
    </tr>
    <tr>
        <td>#SJ<?=$results['id']; ?> </td><td><?=$results['academic_level']; ?></td><td ><?=$results['details']; ?></td>

    </tr>
</table>
<?php
endwhile;
?>

Remove all $i related code. Just move your fetch statement to while condition , like the following:

while( $results=$records->fetch(PDO::FETCH_ASSOC))

You need to include the html code in the while loop because you want to display all of the orders.

I'm using this method, try this out.

Start while in first php section

<?php
$username = $_SESSION['username'];
$sql = $db->prepare("SELECT * FROM tableName WHERE username = '$username' ");
$sql->execute();

   while($results=$sql->fetch(PDO::FETCH_ASSOC)){

?> 

After that the html section coming:

<h3>Your Orders</h3>
<table >
    <tr >
        <th>Order Number</th><th>Academic Level</th><th>Order Details</th>Manage Order</th>
    </tr>
    <tr>
        <td><?php echo $results['id']; ?> </td><td><?php echo $results['academic_level']; ?></td><td ><?php echo $results['details']; ?></td>

    </tr>
</table>

and here the ending

<?php
}
?>

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