I am trying to design my website but for some reason when I add php it's creating a new row per product instead of 3 products per row.
<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>
You need to render your products in columns per row, ie build a grid. I've put together a small demo that shows how you can render 3 products per row.
The function renderProduct()
invoked in the foreach()
mimmicks the while
loop you're using to retrieve the products from the database; it generates a column
per product.
The code uses HEREDOC as it helps to separate PHP and HTML, while allowing injection of PHP variables( variables are expanded) , lovely.
<?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;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.