ProductModel.php 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. <?php
  2. namespace Models;
  3. class ProductModel
  4. {
  5. private \PDO $pdo;
  6. public function __construct()
  7. {
  8. $dbFile = $_ENV['DB_FILE'];
  9. $dbPath = __DIR__ . '/../' . $dbFile;
  10. $this->pdo = new \PDO("sqlite:" . $dbPath);
  11. $this->pdo->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION);
  12. }
  13. public function getProducts(int $companyId): array
  14. {
  15. $stmt = $this->pdo->prepare("SELECT * FROM product WHERE company_id = :company_id AND product_flag = 'a'");
  16. $stmt->execute(['company_id' => $companyId]);
  17. return $stmt->fetchAll(\PDO::FETCH_ASSOC);
  18. }
  19. public function createProduct(string $name, float $price, int $categoryId, int $companyId): bool
  20. {
  21. $stmt = $this->pdo->prepare("INSERT INTO product (product_name, product_price, category_id, company_id, product_flag)
  22. VALUES (:name, :price, :category_id, :company_id, 'a')");
  23. return $stmt->execute([
  24. 'name' => $name,
  25. 'price' => $price,
  26. 'category_id' => $categoryId,
  27. 'company_id' => $companyId
  28. ]);
  29. }
  30. public function updateProduct(int $productId, int $companyId, ?string $productName = null, ?float $productPrice = null): bool
  31. {
  32. $sql = "UPDATE product SET ";
  33. $params = [];
  34. if ($productName !== null) {
  35. $sql .= "product_name = :product_name";
  36. $params['product_name'] = $productName;
  37. }
  38. if ($productPrice !== null) {
  39. if ($productName !== null) {
  40. $sql .= ", ";
  41. }
  42. $sql .= "product_price = :product_price";
  43. $params['product_price'] = $productPrice;
  44. }
  45. if (empty($params)) {
  46. return false; // Nothing to update
  47. }
  48. $sql .= " WHERE product_id = :product_id AND company_id = :company_id AND product_flag = 'a'";
  49. $params['product_id'] = $productId;
  50. $params['company_id'] = $companyId;
  51. $stmt = $this->pdo->prepare($sql);
  52. return $stmt->execute($params);
  53. }
  54. public function deleteProduct(int $productId, int $companyId): bool
  55. {
  56. $stmt = $this->pdo->prepare("UPDATE product SET product_flag = 'd'
  57. WHERE product_id = :product_id AND company_id = :company_id AND product_flag = 'a'");
  58. return $stmt->execute(['product_id' => $productId, 'company_id' => $companyId]);
  59. }
  60. }