34567-vm/products/read.php
2025-10-02 20:43:00 +00:00

29 lines
771 B
PHP

<?php
require_once __DIR__ . '/../db/config.php';
header('Content-Type: application/json');
$id = $_GET['id'] ?? null;
try {
$pdo = db();
if ($id) {
$stmt = $pdo->prepare("SELECT * FROM products WHERE id = ?");
$stmt->execute([$id]);
$product = $stmt->fetch();
if ($product) {
echo json_encode($product);
} else {
http_response_code(404);
echo json_encode(['error' => 'Product not found']);
}
} else {
$stmt = $pdo->query("SELECT * FROM products");
$products = $stmt->fetchAll();
echo json_encode($products);
}
} catch (PDOException $e) {
http_response_code(500);
echo json_encode(['error' => 'Database error: ' . $e->getMessage()]);
}