选择数据库中的 php 表 <th> 和 <td> 但它们在正确的索引位置不匹配

Posted

技术标签:

【中文标题】选择数据库中的 php 表 <th> 和 <td> 但它们在正确的索引位置不匹配【英文标题】:php table <th> and <td> from Database Selected but they are not Matching in the right indexing position 【发布时间】:2021-12-05 00:30:49 【问题描述】:

所有开发人员。 我正在开发学校管理系统,在数据库中,我有两张表,一张是针对科目的,另一张是为获得的科目分数而设计的,它被称为分数。 所以我试图获取主题名称作为表头

我在此查询下方有另一个查询,我正在尝试从分数中获取表数据。

此时,我未能从分数表中匹配主题名称及其分数。

这是我的代码:

<table class="table table-striped table-bordered">
<head>
 <tr>
<?php
// Query for Subject Names

    $view_subject = $config->prepare("SELECT * FROM subjects");
    $view_subject->execute(); 
    while($row = $view_subject->fetch())
        $sub_name = htmlspecialchars($row['sub_name']);
 ?>
 <th class="text-center"style="background-color:#395C7F;color:#fff;"><?php echo $sub_name;?></th>

<?php  ?>
 
</tr>
</thead>
<body>

<?php
// Query for Subject Scores
$view_scores = $config->prepare("SELECT * FROM scores INNER JOIN subjects ON scores.score_sub_id = subjects.sub_id WHERE scores.std_rand = :random_id ORDER BY scores.score_sub_id ASC");
$view_scores->execute(['random_id' => $rand_ID]); 
while($row = $view_scores->fetch())

$score_id = htmlspecialchars($row['score_id']);
$score_sub_id = htmlspecialchars($row['score_sub_id']);
$score_mid_amount = htmlspecialchars($row['score_mid_amount']);
$score_final_amount = htmlspecialchars($row['score_final_amount']);

?>

<tr>
    <td class="text-black" data-title="Subject"><?php echo $score_mid_amount;?></td>
</tr>

<?php  ?>
</tbody>
</table>

数据库图片: 1- 主题表

2- 分数表

** 浏览器界面 **

【问题讨论】:

在您的第二个循环中,您在循环中输入了错误的“”,以及为什么会发生这种情况。 ' ' 是一个新行,您需要遍历所有 ''s 才能切换到下一行。 另外,如果你有不止一行,你需要另一个循环只为这些行 - 另一个循环为 '' 包装 '' 循环......:) 【参考方案1】:

在第二个循环中,您输入了 '

' 包装每个 '',这意味着每个都到达不同的行,' 应该与 ' 一样多' 对于每一行......所以:
<?php
// Query for Subject Scores
$view_scores = $config->prepare("SELECT * FROM scores INNER JOIN subjects ON scores.score_sub_id = subjects.sub_id WHERE scores.std_rand = :random_id ORDER BY scores.score_sub_id ASC");
$view_scores->execute(['random_id' => $rand_ID]); 
?>
<tr> 
<?php
while($row = $view_scores->fetch())

$score_id = htmlspecialchars($row['score_id']);
$score_sub_id = htmlspecialchars($row['score_sub_id']);
$score_mid_amount = htmlspecialchars($row['score_mid_amount']);
$score_final_amount = htmlspecialchars($row['score_final_amount']);

?>


    <td class="text-black" data-title="Subject"><?php echo $score_mid_amount;?></td>


<?php  ?>
</tr>
</tbody>
</table>

这应该可以修复您的表格,但只会创建一行!如果您有不止一行,则需要添加另一个循环来包装这一行,它将在内循环之外创建新的“

”。

顺便说一句:我假设第二个 while 循环与第一个循环完全一样长......因为如果它的长度不同,那么每行每

应该有相同数量的 排序方式与您将遇到问题的方式相同...可以通过调整您的 SELECT 或创建一个带有 ids 的数组并根据第一个带入的键将第二个循环中的数据注入其中来解决。

【讨论】:

以上是关于选择数据库中的 php 表 <th> 和 <td> 但它们在正确的索引位置不匹配的主要内容,如果未能解决你的问题,请参考以下文章

使用 php 保存可编辑表中的值

我需要帮助处理数据表格PHP / HTML [关闭]

PHP / Jquery创建和操作表

如何将 html 风格化表与 php 和 sql 连接起来

如何将数据库表头用于 html <th> 表头标记

如何使用 PHP DOMDocument 链接类似元素?