Advertisement
Guest User

Untitled

a guest
May 23rd, 2019
90
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.13 KB | None | 0 0
  1. <?php
  2. class Product
  3. {
  4.  
  5. // database connection and table name
  6. private $conn;
  7. private $table_name = "products";
  8.  
  9. // object properties
  10. public $id;
  11. public $name;
  12. public $description;
  13. public $price;
  14. public $category_id;
  15. public $category_name;
  16. public $created;
  17.  
  18. // constructor with $db as database connection
  19. public function __construct($db)
  20. {
  21. $this->conn = $db;
  22. }
  23.  
  24. // read products
  25. function read()
  26. {
  27.  
  28. // select all query
  29. $query = "SELECT
  30. c.name as category_name, p.id, p.name, p.description, p.price, p.category_id, p.created
  31. FROM
  32. " . $this->table_name . " p
  33. LEFT JOIN
  34. categories c
  35. ON p.category_id = c.id
  36. ORDER BY
  37. p.created DESC";
  38.  
  39. // prepare query statement
  40. $stmt = $this->conn->prepare($query);
  41.  
  42. // execute query
  43. $stmt->execute();
  44.  
  45. return $stmt;
  46. }
  47. // create product
  48. function create()
  49. {
  50.  
  51. // query to insert record
  52. $query = "INSERT INTO
  53. " . $this->table_name . "
  54. SET
  55. name=:name, price=:price, description=:description, category_id=:category_id, created=:created";
  56.  
  57. // prepare query
  58. $stmt = $this->conn->prepare($query);
  59.  
  60. // sanitize
  61. $this->name = htmlspecialchars(strip_tags($this->name));
  62. $this->price = htmlspecialchars(strip_tags($this->price));
  63. $this->description = htmlspecialchars(strip_tags($this->description));
  64. $this->category_id = htmlspecialchars(strip_tags($this->category_id));
  65. $this->created = htmlspecialchars(strip_tags($this->created));
  66.  
  67. // bind values
  68. $stmt->bindParam(":name", $this->name);
  69. $stmt->bindParam(":price", $this->price);
  70. $stmt->bindParam(":description", $this->description);
  71. $stmt->bindParam(":category_id", $this->category_id);
  72. $stmt->bindParam(":created", $this->created);
  73.  
  74. // execute query
  75. if ($stmt->execute()) {
  76. return true;
  77. }
  78.  
  79. return false;
  80. }
  81. }
  82. ?>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement