public function add() { Functions::EditorAuthorization(); if (isset($_POST['addItemButton'])) { $name = $_POST['name']; $price = (int) $_POST['price']; $desc = $_POST['desc']; $quantity = (int) $_POST['quantity']; $condition = $_POST['condition']; $pic = $_POST['pic']; $category = $_POST['category']; $errors = []; if (strlen($name) == 0) { $errors[] = "Invalid product name"; } if ($quantity == 0) { $errors[] = "Invalid quantity"; } if (count($errors) == 0) { $product = new ProductBindingModel(); $product->setName($name); $product->setQuantity($quantity); $product->setPrice($price); $product->setCategory($category); $product->setCondition($condition); $product->setDescription($desc); $product->setPicture($pic); $productModel = new ProductsModel(); try { $productModel->addProduct($product); } catch (\Exception $e) { View::$viewBag['errors'] = $e->getMessage(); } } else { View::$viewBag['errors'] = $errors; } } $categoriesModel = new CategoriesModel(); $categories = $categoriesModel->getAllCategories(); $model["categories"] = $categories; return new View($model); }
public function addProduct(ProductBindingModel $p) { $conn = DB::connect(); $insertProductSql = 'INSERT INTO products(name, price, added_on, description, quantity, `condition`, picture) VALUES( "' . $p->getName() . '", "' . $p->getPrice() . '", "' . time() . '", "' . $p->getDescription() . '", "' . $p->getQuantity() . '", "' . $p->getCondition() . '", "' . $p->getPicture() . '" )'; if (!$conn->query($insertProductSql)) { throw new \Exception("Database error"); } $getProductId = $conn->query('SELECT id FROM products WHERE name="' . $p->getName() . '" ORDER BY added_on DESC LIMIT 1')->fetch(); $addCategorySql = 'INSERT INTO category_product(category_id, product_id) VALUES("' . $p->getCategory() . '", "' . $getProductId["id"] . '")'; if (!$conn->query($addCategorySql)) { throw new \Exception("Database error"); } View::$viewBag['successMessage'] = "Product successfully added"; }