PHP如何从数据库拉取不同文章填充到每张卡片中?
问题根源
你目前的代码逻辑存在嵌套错误:
- 循环范围过大:数据库读取的
while循环包含了整行布局容器(<section>、<div class="container">、<div class="row">),每读取1篇文章就生成一整行页面结构 - 卡片重复编写:单个循环内部写了2个完全相同的卡片渲染代码,所以同一行的两张卡片都会读取当前循环的同一篇文章数据,导致重复展示
修正方案
将布局容器移到循环外部,仅对单个卡片列做循环即可,同时注意你当前同时引入了Bootstrap5和Bootstrap4的资源,会出现样式冲突,建议统一使用同一个版本的Bootstrap资源。
修正后的完整代码如下:
<html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous"> <title>Document</title> </head> <body> <?php require 'config.php'; $sql = "SELECT * FROM contents"; $query_run = mysqli_query($con, $sql); $check_data = mysqli_num_rows($query_run) > 0; ?> <!-- 布局容器移到循环外部,全局只生成一次 --> <section> <div class="container"> <div class="row"> <?php if($check_data) { // 仅循环单个卡片列部分 while($row = mysqli_fetch_assoc($query_run)) { ?> <div class="col-4"> <div class="card mt-5"> <div class="card-body"> <img src="images/<?php echo $row['images'] ?>" alt="" class="card-img-top"> <h2 class="card-title"><?php echo $row['title']; ?></h2> <h3 class="card-desc"><?php echo $row['short_desc']; ?></h3> </div> </div> </div> <?php } } ?> </div> </div> </section> <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.bundle.min.js" integrity="sha384-MrcW6ZMFYlzcLA8Nl+NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP+JcXn/tWtIaxVXM" crossorigin="anonymous"></script> </body> </html>
修改后每行的3张卡片(col-4对应一行3列)都会自动加载不同的文章数据,超出3篇的内容会自动换行展示。
内容的提问来源于stack exchange,提问作者coding_noob
相关产品推荐
相关产品推荐

