php - PHP 为每个产品创建一行,而不是每行 3 个产品
问题描述
我正在尝试设计我的网站,但由于某种原因,当我添加 php 时,它会为每个产品创建一个新行,而不是每行 3 个产品。
<main>
<div class="container">
<div class="row">
<div class="col">
<div class="card" style="width: 18rem;height: 400px;">
<?php
$query = "SELECT products.ProductName, products.Price, products.Weight, products.image FROM products";
$result = $link->query($query);
while ($row = mysqli_fetch_assoc($result)) {
?>
<img src="<?php echo "{$row['image']}" ?>" width="100%">
<div class="card-body"><br>
<h5 class="card-title"><?php echo "{$row['ProductName']}" ?></h5>
<p>Weight: <?php echo "{$row['Weight']}" ?></p>
<p>€<?php echo "{$row['Price']}" ?></p>
</div>
<?php
}
?>
</div>
</div>
</div>
</div>
</main>
解决方案
您需要在每行的列中呈现您的产品,即构建一个网格。我整理了一个小演示,展示了如何每行渲染 3 个产品。
在模仿你用来从数据库中检索产品的循环renderProduct()
中调用的函数;它生成每个产品。foreach()
while
column
该代码使用HEREDOC,因为它有助于分离PHP和HTML,同时允许注入PHP变量(变量被扩展),可爱。
<?php
function renderProduct($product = []) {
$htmlProduct = <<<HEREDOC
<div class="col">
<div class="card" style="width: 18rem;height: 400px;">
<img src="{$product["img"]}" width="100%">
<div class="card-body"><br>
<h5 class="card-title">{$product["name"]}</h5>
<p>Weight: {$product["weight"]}</p>
<p>€{$product["price"]}</p>
</div>
</div>
</div>
HEREDOC;
return $htmlProduct;
}
$htmlStart = <<<HEREDOC
<!DOCTYPE html> <html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title>demo</title>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">
<link rel="stylesheet" href="something.css">
</head>
<body>
<div class="container">
<div class="row">
HEREDOC;
$htmlEnd = <<<HEREDOC
</div> <!-- close row -->
</div> <!-- close container -->
</body>
</html>
HEREDOC;
// render page
echo $htmlStart;
$products = [
['img' => '1.png', 'name' => 'prod1', 'weight' => '300g', 'price' => '30'],
['img' => '2.png', 'name' => 'prod2', 'weight' => '400g', 'price' => '40'],
['img' => '3.png', 'name' => 'prod3', 'weight' => '500g', 'price' => '50'],
['img' => '4.png', 'name' => 'prod4', 'weight' => '600g', 'price' => '60'],
['img' => '5.png', 'name' => 'prod5', 'weight' => '700g', 'price' => '70'],
['img' => '6.png', 'name' => 'prod6', 'weight' => '800g', 'price' => '80'],
];
foreach($products as $prod) {
echo renderProduct($prod);
}
echo $htmlEnd;
推荐阅读
- firebase - 进行firebase身份验证的正确方法是什么
- kubernetes - 使用 K8S 横向扩展
- google-app-engine - 使用 Google App Engine Image API 时有什么方法可以配置平移/裁剪位置?
- swift - 将多个按钮链接到同一个站点 xcode
- react-native - 无法使用 AsyncStorage API 存储登录的用户数据
- azure - 将资源组所有者授予个人和企业帐户
- java - “else if”语句中的逻辑运算符
- java - spring boot-无法读取yaml属性文件application.yml
- android - android/view/View$OnUnhandledKeyEvent 监听器错误
- c++ - 将基本类型数组中的内存重用于不同(但仍然是基本)类型数组是否合法