[英]PHP Creating one row for each product instead of 3 products per row
我正在尝试设计我的网站,但由于某种原因,当我添加 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 个产品。
在foreach()
) 中调用的 function renderProduct()
) 模仿了您用于从数据库中检索产品的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;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.