如何将多个行值显示到具有不同列的单个行中?

时间:2016-01-04 01:20:49

标签: php mysql echo rows

<table width="770px" cellpadding="2" cellspacing="0" style="float: right;">
    <tr>
<th width="20%">A</th>
<th width="20%">B</th>
<th width="20%">C</th>
<th width="20%">D</th>
<th colspan=2 width="20%">Actions</th>
</tr>
<tbody>
<?php 
            $sql = mysql_query("SELECT * FROM answers ORDER BY question_id DESC");
            if(!$sql){
                die( "Database selection failed: " . mysql_error());
            }
            while ($row = mysql_fetch_assoc($sql)) {
                    echo "<form method=\"post\" action=\"editQuestions.php\">";
                    echo "<tr height=\"30px\"> ";
                        for($ctrCell=1;$ctrCell<=4;$ctrCell++){
                        echo "<td >";
                        echo $row['answer'];
                        echo "</td>";
                        }
                        echo "<td style=\"border-left: solid 1px #00478F;\" class=\"action\"><input type=\"submit\" name=\"btnAction\" value=\"EDIT\"></td>";
                        echo "<td style=\"border-right: solid 1px #00478F;\" class=\"action\"><input type=\"submit\" name=\"btnAction\" value=\"DELETE\"></td>";
                    echo "</tr>";
                    echo "</form>";
                }

?>


</tbody>
</table>

SCREENSHOT of WEBPAGE SCREENSHOT of MySQL DB

之前我尝试过使用JOIN,但它做的是同样的事情。我只有一张桌子,现在我正在尝试使用两张桌子。但是,我似乎无法弄清楚如何正确显示每个问题的行,A,B,C,D。

附加的图像是网站管理页面上的图像,另一个是数据库本身。

1 个答案:

答案 0 :(得分:1)

因为这段代码for($ctrCell=1;$ctrCell<=4;$ctrCell++){ 最好预定义数据,在执行查询后构建数组 $rows = mysql_fetch_assoc($sql); $data = []; foreach($rows as $row){ $data[$row['question_id']][] = $row['answer']; } 就这样做

echo "<form method=\"post\" action=\"editQuestions.php\">";
foreach ($data as $row) {
    echo "<tr>";
    foreach ($row as $answer) {
        echo "<td>" . $answer . "</td>";
     } 
    echo "</tr>";
}
echo "</form>";

希望有所帮助。