Hi! Could we please enable some services and cookies to improve your experience and our website?
Online Sandbox for SQL and PHP: Write, Run, Test, and Share SQL Queries and PHP Code
CREATE TABLE categories (
id INT PRIMARY KEY,
title VARCHAR(64)
);
INSERT INTO categories VALUES (1, 'Cat1'),(2, 'Cat2');
CREATE TABLE prices (
id INT PRIMARY KEY,
title VARCHAR(64),
price DECIMAL(9, 2),
type VARCHAR(64),
category_id INT REFERENCES categories(id)
);
INSERT INTO prices VALUES
(1, 'Price1', 10.2, 'kg', 1),
(2, 'Price2', 20.2, 'm2', 2);
<?php
function get_categories($pdo)
{
$stmt = $pdo->prepare("SELECT * FROM `categories`");
$stmt->execute();
return $stmt->fetchAll(PDO::FETCH_ASSOC);
}
function get_prices_by_category($pdo, $category_id)
{
$stmt = $pdo->prepare("SELECT * FROM `prices` WHERE category_id = ?");
$stmt->execute([$category_id]);
return $stmt->fetchAll(PDO::FETCH_ASSOC);
}
$categories = get_categories($pdo);
foreach ($categories as $category) {
echo '<h3>'.$category['title'].'</h3>
<div class="cblock">';
$prices = get_prices_by_category($pdo, $category['id']);
foreach ($prices as $price) {
echo '<div class="pricelist-row">
<div class="service">' . $price["title"] . '</div>
<div class="price">от ' . $price["price"] . ' руб/' . $price["type"] . '</div>
</div>';
}
echo '</div>';
}