将数据库中的多行打印到表中

时间:2016-03-29 15:05:56

标签: php mysql

有人能告诉我如何调整或更改此代码以使用PHP将数据库表中的多行打印到html表中吗?每个用户在表中都有不同数量的记录,因此我需要使用某种循环来打印行。

<?php

                    include_once 'dbconfig.php';

                    $statement = $db_con->prepare("SELECT * FROM entry WHERE user_id=:uid");
                    $statement->execute(array(":uid"=>$_SESSION['user_session']));
                    $result=$statement->fetch(PDO::FETCH_ASSOC);

                    ?>

                    <table>
                        <tr>
                        <th>Entry</th>
                            <th>Date</th>
                            <th>Weight</th>
                            <th>BMI</th>
                            <th>Calories Consumed</th>
                            <th>Calories Burned</th>
                            <th>Calorific Deficit</th>
                        </tr>

                    <?php

 while($row = mysql_fetch_array($result)) { 

        $entry = $row["entry_id"];           
        $date = $row["date"]; 
        $weight = $row["weight"];
        $bmi = $row["bmi"]; 
        $consumed = $row["calories_consumed"]; 
        $burned = $row["calories_burned"];
        $deficit = $row["calorie_deficit"]; 

        echo "<tr>
        <td>$entry</td>
        <td>$date</td>
        <td>$weight</td>
        <td>$bmi</td>
        <td>$consumed</td>
        <td>$burned</td>
        <td>$deficit</td>
        </tr>";

}

                    ?>

                        </table>

这当前工作正常,但它只打印出与特定用户相关的第一行,而不是循环并为每条记录打印一行。

已更新为包含while循环

1 个答案:

答案 0 :(得分:0)

while ($row =$statement->fetch(PDO::FETCH_ASSOC)) {
            $title1 = $row["title1"]; 
            $title2 = $row["titl2"]; 
            $title3 = $row["title3"]; 

            echo "<tr> 
            <td>$title1</td>
            <td>$title2</td>
            <td>$title3</td>
             </tr>";
    }