PHP从MySQL查询数据到Div仅显示第一条的问题求助
问题分析与解决方案
你遇到的只显示第一条数据的问题,核心原因是HTML中重复使用了唯一的id属性,同时代码可以进一步简化优化,具体如下:
1. 核心问题:重复的ID属性
HTML规范要求id在整个文档中必须是唯一的,你在循环生成元素时,给每个重复的模块都用了相同的id(比如itemcomponent-attireandaccssories、itemcomponenttitle等),浏览器遇到重复id时会无法正确识别后续元素,这就是你只能看到第一条数据的关键原因。
2. 优化后的代码
我们可以把id替换成可重复的class,同时简化PHP的查询结果处理逻辑(不需要先把数据存入数组再循环):
修正后的完整代码
<?php $sql = "SELECT budget_id, item, budget, paid, spent FROM budget WHERE title ='attireandaccssories' ORDER BY budget_id "; $resultset = mysqli_query($con, $sql) or die("database error:". mysqli_error($con)); ?> <?php while($row = mysqli_fetch_assoc($resultset)){ ?> <div class="itemcomponent-attireandaccssories"> <div class="itemcomponentjscontainer-attireandaccssories"> <div class="itemcomponenttitle"><?php echo htmlspecialchars($row['item']); ?></div> <div class="itemcomponentdelete" data-budget-id="<?php echo $row['budget_id']; ?>" > <i class="fa fa-trash-o" aria-hidden="true fa-2x"></i> </div> <div class="itemcomponentspent"><?php echo htmlspecialchars($row['spent']); ?></div> <div class="itemcomponentpaid"><?php echo htmlspecialchars($row['paid']); ?></div> <div class="itemcomponentbudget" ><?php echo htmlspecialchars($row['budget']); ?> </div> <div style="clear: both;" class="clearall"></div> </div> </div> <?php } ?>
3. 关键改进点说明
- 替换id为class:所有重复出现的元素标识从
id改为class,确保浏览器能正确渲染每一条数据对应的模块。 - 直接遍历结果集:用
while循环直接读取查询结果,省去了中间数组存储的步骤,代码更简洁高效,也避免了数组操作可能带来的潜在问题。 - 安全输出:添加
htmlspecialchars()函数转义输出内容,防止XSS攻击,确保页面安全。 - 规范自定义属性:把
budget_id=<?php echo $budget_id[$i]; ?>改为符合HTML5标准的data-budget-id="<?php echo $row['budget_id']; ?>",后续JavaScript操作数据时更规范方便。
内容的提问来源于stack exchange,提问作者alexvin
相关产品推荐
相关产品推荐

