You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将PHP数据库查询循环插入到PHP生成的Overlay Div中?

实现方法

核心思路是先把数据库中的所有服务标题提前存入数组,再在生成容器的循环中,将对应标题插入到overlay容器内部,确保DOM结构正确。

步骤1:预存数据库查询结果

先把从MySQL获取的服务标题存入一个数组,方便后续循环调用:

$serviceTitles = [];
if($resultCheck > 0){
    while($row = $result->fetch_assoc()){
        $serviceTitles[] = $row['service_title'];
    }
}

步骤2:修改容器生成循环

在生成6个服务容器的循环中,根据当前循环的索引,从数组中取出对应标题(如果数组长度不足6,默认留空),并嵌入到$element4的overlay div内:

$element = "<div class='service'>";
$element2= "<div class='img_container'>";
$element3= "<img class='service_img'/></div>";
$element5= "<div class='service_details'></div></div>";
$count = 6;

foreach( range(1,$count) as $index){
    // 计算数组索引(从0开始)
    $titleIndex = $index - 1;
    // 取出对应标题,没有则为空字符串
    $title = isset($serviceTitles[$titleIndex]) ? $serviceTitles[$titleIndex] : '';
    // 动态生成包含标题的overlay
    $element4 = "<div class='overlay'><h3 class='service_title'>{$title}</h3></div>";
    
    echo $element, $element2, $element3, $element4, $element5;
}

问题根源

你之前的代码是先把6个容器全部输出完,再单独输出所有h3标签,这些h3会直接出现在容器的外部,自然DOM位置错误。现在通过预存数据+循环内嵌入的方式,让每个标题精准对应到每个容器的overlay内部。

内容的提问来源于stack exchange,提问作者Ashley Serrano-Ziel

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.24 05:37:08