function main() { $product = array(); $errors = empty_errors(); if (is_postback()) { // подключаемся к базе данных $dbh = db_connect(); $post_result = add_product($dbh, $product, $errors); db_close($dbh); if ($post_result) { // перенаправляем на список товаров render('sucsess_register', array()); } else { render('BD_ProductInsert_T', array('form' => $_POST, 'file' => $_FILES, 'errors' => $errors)); } } else { // отправляем пользователю чистую форму для входа render('BD_ProductInsert_T', array('form' => array(), 'errors' => array())); } }
function main() { // подключаемся к базе данных $dbh = db_connect(); $product = array(); $errors = array(); if (is_postback()) { $post_result = add_product($dbh, $product, $errors); if ($post_result) { db_close($dbh); // перенаправляем на список товаров redirect('./'); } } // считываем список товаров и категорий $categories = db_category_find_all($dbh); $products = db_product_find_all($dbh); // выводим результирующую страницу render('product_list', array('categories' => $categories, 'products' => $products, 'form' => $_POST, 'errors' => $errors)); // закрываем соединение с базой данных db_close($dbh); }
} else { if (isset($_GET['action'])) { $action = $_GET['action']; } else { $action = 'display_all'; } } if ($action == 'display_all') { $all_products = get_products(); include 'product_list.php'; } else { if ($action == 'delete_record') { $product_item = $_POST['product_item']; delete_product($product_item); header('Location: .'); } else { if ($action == 'add_record') { $product_item = $_POST['product_item']; $name = $_POST['name']; $version = $_POST['version']; $release_date = $_POST['release_date']; if (empty($product_item) || empty($name) || empty($version) || empty($release_date)) { $error = "Invalid product data. Check all fields and try again."; header("Location: .?error={$error}"); } else { add_product($product_item, $name, $version, $release_date); header('Location: .'); } } } }
function save_product() { $data = array('product' => array('name' => '', 'description' => '', 'price' => 0, 'url' => '')); $errors = array(); $data['success'] = false; if (empty($_POST['action'])) { $errors['action'] = 'Внутренняя ошибка'; } if ($_POST['action'] == 'edit') { if (empty($_POST['id'])) { $errors['action'] = 'Внутренняя ошибка'; } else { $data['product']['id'] = $_POST['id']; } } if (empty($_POST['name'])) { $errors['name'] = 'Нужно указать название товара'; } else { $data['product']['name'] = $_POST['name']; } if (empty($_POST['price'])) { $errors['price'] = 'Нужно указать цену'; } else { $data['product']['price'] = trim($_POST['price']); preg_match('/^(?:\\d+|\\d{1,3}(?:,\\d{3})+)(?:\\.\\d+)?$/', $data['product']['price'], $match); if (empty($match)) { $errors['price'] = 'Цена в не правильном формате, пример: 1232.20'; } } if (!empty($_POST['description'])) { $data['product']['description'] = $_POST['description']; } if (!empty($_POST['url'])) { $data['product']['url'] = $_POST['url']; } if (!empty($errors)) { $data['errors'] = $errors; } else { switch ($_POST['action']) { case 'edit': if (edit_product($data['product'])) { $data['success'] = true; } break; case 'add': if (add_product($data['product'])) { $data['success'] = true; } break; } clear_cache(); } // return all our data to an AJAX call echo json_encode($data); }
$form_buy[$index] = new Form('form_buy' . $index); $form_buy[$index]->method('POST'); $form_buy[$index]->add('Submit', 'submit')->value("Ajouter au panier"); $form_buy[$index]->bound($_POST); //construct a array with the product_id array_push($tbx_index, $index); } include PATH_VIEW . 'view_table.php'; } //end of for loop in cat $error_buy = array(); foreach ($tbx_index as $value) { //which product user wants to buy if ($form_buy[$value]->is_valid($_POST)) { $infos_product_tobuy = infos_product($value); //Dont have enough money in the account if (user_balance($_GET['id']) < $infos_product_tobuy['product_price']) { $error_buy[] = "Solde insuffisant pour acheter cet objet, vous pouvez recharger votre compte dans la partie Banque"; } elseif (uniq_prdct_in_cart($value, $_GET['id']) != 0) { buy_product($value, $_GET['id']); } else { add_product($value, $_GET['id'], uniq_prdct_in_cart($value, $_GET['id'])); } //end of user_balance //echo print_r(infos_product($value)); //buy_product($value,$_GET['id'],nbr_portion_prdct($value)); include PATH_VIEW . 'view_store.php'; } } } //end of user_connected
header("Location: .?action=show_add_form"); } } else { if ($action == 'show_add_form') { include 'product_add.php'; } else { if ($action == 'add_product') { $code = filter_input(INPUT_POST, 'code'); $name = filter_input(INPUT_POST, 'name'); $price = filter_input(INPUT_POST, 'price'); $description = filter_input(INPUT_POST, 'description'); $img = filter_input(INPUT_POST, 'img'); if ($code == NULL || $name == NULL || $price == NULL || $price == FALSE) { $message = "Invalid product data. Check all fields and try again."; } else { add_product($code, $name, $price, $description, $img); header("Location: .?show_add_form"); } } else { if ($action == 'upload_image') { $target_dir = $_SERVER['DOCUMENT_ROOT'] . "/media/products/"; $target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]); $uploadOk = 1; $imageFileType = pathinfo($target_file, PATHINFO_EXTENSION); // Check if image file is a actual image or fake image if (isset($_POST["submit"])) { $check = getimagesize($_FILES["fileToUpload"]["tmp_name"]); if ($check !== false) { $message = "File is an image - " . $check["mime"] . "."; $uploadOk = 1; } else {
if ($page > $pages_count) { $page = $pages_count; } //если пользователь в адресную строку введет число большее чем реальное кол-во страниц $start_position = ($page - 1) * $perpage; //начальная позиция вывода товара (для запроса) /*постраничная навигация*/ //хлебные крошки, считаем имя родителя $brand_name = brand_name($category); $products = products($category, $start_position, $perpage); //получаем массив из модели break; case 'add_product': $brand_id = (int) $_GET['brand_id']; if ($_POST) { if (add_product()) { redirect("?view=cat&category={$brand_id}"); } else { redirect(); } } break; case 'edit_product': $goods_id = (int) $_GET['goods_id']; $get_product = get_product($goods_id); $brand_id = $get_product['goods_brandid']; // если есть базовая картинка if ($get_product['img'] != "no_image.jpg") { $baseimg = '<img class="delimg" rel="0" width="48" src="' . PRODUCTIMG . $get_product['img'] . '" alt="' . $get_product['img'] . '">'; } else { $baseimg = '<input type="file" name="baseimg" />';
$cred_results = $db->query($cred_command); $cred_data = $cred_results->fetch_object(); // If username exists, and password exists, and they match a record in the dB, log in the user. if (isset($cred_data->username) && $cred_data->username == $username) { if ($cred_data->password == $pw) { if (isset($cred_data->admin)) { $_SESSION['admin'] = 1; } $_SESSION['sign_in'] = 1; $_SESSION['username'] = $username; $url = "http://" . $_SERVER['HTTP_HOST'] . "/cart02/cart.php"; ob_clean(); header("Location: " . $url) or die("didn't redirect from login"); } elseif ($cred_data->username == $username && $cred_data->password != $pw) { if ($pass_error == 1) { echo '<span class="form_error">The password you entered is not correct</span>'; } } } } // These if statements call the account update or product update functions when the user has // submitted the form. if (isset($_GET['accts']) && $_GET['accts'] == 1) { acct_update($_POST); } if (isset($_GET['products']) && $_GET['products'] == 1) { product_update($_POST); } if (isset($_GET['add_prod']) && $_GET['add_prod'] == 1) { add_product($_POST); }
$values = array(); if (isset($_POST['function'])) { $function = $_POST['function']; $values = $_POST; } elseif (isset($_GET['function'])) { $function = $_GET['function']; $values = $_GET; } else { $values = file_get_contents('php://input'); $values = (array) json_decode($values); $function = $values['function']; } switch ($function) { case 'add_product': include_once __DIR__ . '/products/add_product.php'; $responseArray['response'] = add_product($values); $responseArray['message'] = 'Successfully added product'; break; case 'get_products': include_once __DIR__ . '/products/get_products.php'; $responseArray['response'] = get_products($values); $responseArray['message'] = 'Products successfully read'; break; case 'update_product': include_once __DIR__ . '/products/update_product.php'; update_product($values); $responseArray['message'] = 'Product successfully updated'; break; case 'add_product_class': include_once __DIR__ . '/products/add_product_class.php'; add_product_class($values);
* Select some products **********************************************/ // Sample data $product_name = 'Fender Telecaster'; // Sample data $cat_id = 1; // Get the products $products = get_products_by_category($cat_id); // Get a product by name $product_by_name = get_product_by_name($product_name); /*************************************** * Delete a product ****************************************/ //print_r($product_by_name); delete_product($product_by_name['productID']); // Delete the product and display an appropriate messge $delete_message = "No rows were deleted."; /*************************************** * Insert a product ****************************************/ // Sample data $category_id = 1; $code = 'hgjh'; $name = 'Blahblah'; $description = 'NA'; $price = '949.99'; // Insert the data add_product($category_id, $code, $name, $description, $price, 0.1); // Display an appropriate message $insert_message = "No rows were inserted."; include 'home.php';
<?php # Adds a product to the cart. When a user press the buy button on the product page, this is called. # The "cart" is just an array, $_SESSION['cart'] include 'db_data.php'; if (isset($_POST['buy']) && !empty($_POST['id']) && !empty($_POST['category'])) { $id = $_POST['id']; $category = $_POST['category']; $bool = add_product($id); header("Location: product.php?id={$id}&category={$category}&added={$bool}"); } else { header("Location: products.php"); } //Add the product id to the cart-session. function add_product($id) { try { if (session_status() == PHP_SESSION_NONE) { session_start(); } $db = new Database_Connection(); $sql = 'SELECT quantity FROM stock WHERE productsid = ?'; $result = $db->param_query($sql, 'i', $id); $data = $result->fetch_assoc(); $db->close_statement(); if ($data['quantity'] < 1) { throw new Exception('Product is not in stock'); } $quantity = 0; if (!empty($_SESSION['cart'][$id])) { $quantity = $_SESSION['cart'][$id];
include 'product_list.php'; } else { if ($action == 'delete_product') { $productCode = filter_input(INPUT_POST, 'productCode'); if ($productCode == NULL || $productCode == FALSE) { $error = "Missing or incorrect technician ID."; include '../errors/error.php'; } else { delete_products($productCode); header("Location: .?action=list_product"); } } else { if ($action == 'show_add_form') { include 'product_add.php'; } else { if ($action == 'add_product') { $productCode = filter_input(INPUT_POST, 'productCode'); $name = filter_input(INPUT_POST, 'name'); $version = filter_input(INPUT_POST, 'version'); $releaseDate = filter_input(INPUT_POST, 'releaseDate'); if ($productCode == null || $productCode == FALSE || $name == NULL || $name == FALSE || $version == NULL || $version == FALSE || $releaseDate == NULL || $releaseDate == FALSE) { $error = "Missing or incorrect technician informatino."; include '../errors/error.php'; } else { add_product($productCode, $name, $version, $releaseDate); header("Location: .?action=list_product"); } } } } }
function vm_check_add_product_form() { if (isset($_POST['inputProduct'])) { $req = new CreateProductRequest(); $req->comment = $_POST['inputComment']; $price = floatval(str_replace(",", ".", $_POST['inputPrice'])); if ($price == 0) { $res = new BaseResponse(); $res->status = false; $res->errorDescription = "Please use valid numbers for price parameter"; return $res; } $req->price = $price; $req->product = $_POST['inputProduct']; $result = add_product($req); return $result; } return ""; }
function add_save() { global $db, $t; $vars = get_input_vars(); $vars['renewal_group'] = preg_replace('|\\(keep default if not sure\\)|', '', $vars['renewal_group']); $p = new product($vars); convert_period_fields($p); $error = validate_product_fields($p); if ($error) { add_product($error); return false; } $product_id = $db->add_product($p->config); if (!$product_id) { $error = "Cannot insert product. INTERNAL ERROR"; } admin_log("Product added {$product_id}"); $t->assign('url', "products.php"); $t->display("admin/product_saved.html"); }
$errors_form_cat[] = "Cette catégorie existe déjà."; } else { $errors_form_cat[] = "Erreur ajout SQL : doublon non identifié présent dans la base de données."; } } else { $errors_form_cat[] = sprintf("Cette catégorie existe déjà."); } } //end of $test } //end of empty(cat_) } else { if ($form_add_product->is_valid($_POST)) { list($product_name, $product_cat, $product_desc, $product_qty, $product_portion, $product_price, $product_img, $product_health_pt, $product_angry_pt, $product_thirst_pt) = $form_add_product->get_cleaned_data('product_name', 'product_cat', 'product_description', 'product_qty', 'product_portion', 'product_price', 'product_img', 'product_health_pt', 'product_angry_pt', 'product_thirst_pt'); //want to add a product $test_product = add_product($product_name, $product_cat, $product_desc, $product_qty, $product_portion, $product_price, $product_img, $product_health_pt, $product_angry_pt, $product_thirst_pt); if ($test_product == true) { $msg_confirm[] = "Votre produit a bien était ajouté."; } else { $error =& $test; if (23000 == $error[0]) { // Le code d'erreur 23000 signifie "doublon" dans le standard ANSI SQL preg_match("`Duplicate entry '(.+)' for key \\d+`is", $error[2], $value_pb); $value_pb = $value_pb[1]; if ($email_addr == $value_pb) { $errors_form_cat[] = "Cette catégorie existe déjà."; } else { $errors_form_cat[] = "Erreur ajout SQL : doublon non identifié présent dans la base de données."; } } else { $errors_form_cat[] = sprintf("Cette catégorie existe déjà.");
$product = Product::find($product_id); if (!$product) { log2("to find the non-existent product id: {$product_id} in add_product.php"); header("Location: index.php"); exit; } if ($_SERVER["REQUEST_METHOD"] == "POST") { $_POST["attr"]["image"] = intval($_POST["attr"]["image"]); //handle add product request if ($_POST["attr"]["image"] <= 0) { $_POST["attr"]["image"] = Image::process_image($_FILES['upload'], $user); } if ($_POST["attr"]["image"] <= 0) { set_msg("Image Error: " . get_error_msg($_POST["attr"]["image"])); } else { $result = add_product($user, $product, $_POST["attr"]); if ($result) { header("Location: cart.php"); exit; } } } $cusproduct = $product->get_cusproduct(); include 'header.php'; include 'menu.php'; ?> <div id="content"> <h3>Customize the <?php echo $cusproduct->get_name(); ?> </h3>
$categories = get_categories(); include 'product_add.php'; break; case 'ADD PRODUCT': $category_id = filter_input(INPUT_POST, 'category_id', FILTER_SANITIZE_NUMBER_INT); $category_id = filter_var($category_id, FILTER_VALIDATE_INT); $product_name = filter_input(INPUT_POST, 'name', FILTER_SANITIZE_STRING); $product_price = filter_input(INPUT_POST, 'price', FILTER_SANITIZE_NUMBER_FLOAT, FILTER_FLAG_ALLOW_FRACTION); $product_price = filter_var($product_price, FILTER_VALIDATE_FLOAT); $product_description = filter_input(INPUT_POST, 'description', FILTER_SANITIZE_STRING); if ($category_id == NULL || $category_id == FALSE || $product_name == NULL || $product_price == NULL || $product_price == FALSE) { $message = "Invalid product data. Check all fields and try again."; $categories = get_categories(); include 'product_add.php'; } else { $product_id = add_product($product_name, $product_price, $product_description, $category_id); add_image($product_id); header("Location: .?action=grid_products"); } break; case 'edit_product_form': $categories = get_categories(); $product_id = filter_input(INPUT_GET, 'product_id', FILTER_SANITIZE_NUMBER_INT); $product_id = filter_var($product_id, FILTER_VALIDATE_INT); $product = get_product($product_id); include 'product_edit.php'; break; case 'UPDATE': $product_id = filter_input(INPUT_POST, 'product_id', FILTER_SANITIZE_NUMBER_INT); $product_id = filter_var($product_id, FILTER_VALIDATE_INT); $category_id = filter_input(INPUT_POST, 'category_id', FILTER_SANITIZE_NUMBER_INT);
<?php include 'template/header.php'; include 'template/menu.php'; ?> <?php if (!empty($_POST['submit'])) { $product_image_url = image_upload(); if (isset($product_image_url)) { $add_product = add_product($_POST['product_name'], $product_image_url, $_POST['category_id'], $_POST['unit_price']); if ($add_product == 1) { $message = "Product has been added."; } else { $errormessage = "Something wrong. Please Try Again!!"; } } else { $errormessage = "Product Image is invalid. Please Try Again!!"; } } $all_category = all_category(); //for select box $all_product = all_product(); /*******************************delete product********************************************/ if (!empty($_GET['delete'])) { $delete_product = delete_product($_GET['delete']); if ($delete_product == 1) { header('Location:product.php'); } else { $errormessage = "Something wrong. Please try again!!.";
include 'product_add_edit.php'; break; case 'add_product': $category_id = filter_input(INPUT_POST, 'category_id', FILTER_VALIDATE_INT); $code = filter_input(INPUT_POST, 'code'); $name = filter_input(INPUT_POST, 'name'); $description = filter_input(INPUT_POST, 'description'); $price = filter_input(INPUT_POST, 'price', FILTER_VALIDATE_FLOAT); $discount_percent = filter_input(INPUT_POST, 'discount_percent'); if ($category_id === FALSE || $code == NULL || $name == NULL || $description == NULL || $price === FALSE || $discount_percent === FALSE) { $error = 'Invalid product data. Check all fields and try again.'; include '../../errors/error.php'; } else { $categories = get_categories(); $product_id = add_product($category_id, $code, $name, $description, $price, $discount_percent); $product = get_product($product_id); include 'product_view.php'; } break; case 'update_product': $product_id = filter_input(INPUT_POST, 'product_id', FILTER_VALIDATE_INT); $category_id = filter_input(INPUT_POST, 'category_id', FILTER_VALIDATE_INT); $code = filter_input(INPUT_POST, 'code'); $name = filter_input(INPUT_POST, 'name'); $description = filter_input(INPUT_POST, 'description'); $price = filter_input(INPUT_POST, 'price', FILTER_VALIDATE_FLOAT); $discount_percent = filter_input(INPUT_POST, 'discount_percent'); if ($product_id === FALSE || $category_id === FALSE || $code === NULL || $name === NULL || $description === NULL || $price === FALSE || $discount_percent === FALSE) { $error = 'Invalid product data. Check all fields and try again.';
} if ($action == 'list_products') { $products = get_products(); include 'product_list.php'; } else { if ($action == 'delete_product') { $product_code = filter_input(INPUT_POST, 'product_code'); delete_product($product_code); header("Location: ."); // redirect request returns to the same page } else { if ($action == 'show_add_form') { include 'product_add.php'; } else { if ($action == 'add_product') { $code = filter_input(INPUT_POST, 'code'); $name = filter_input(INPUT_POST, 'name'); $version = filter_input(INPUT_POST, 'version', FILTER_VALIDATE_FLOAT); $release_date = filter_input(INPUT_POST, 'release_date'); // Validate the inputs if ($code === NULL || $name === FALSE || $version === NULL || $version === FALSE || $release_date === NULL) { $error = "Invalid product data. Check all fields and try again."; include '../errors/error.php'; } else { add_product($code, $name, $version, $release_date); header("Location: ."); } } } } }
if ($action == 'delete_product') { $product_id = filter_input(INPUT_POST, 'product_id', FILTER_VALIDATE_INT); $category_id = filter_input(INPUT_POST, 'category_id', FILTER_VALIDATE_INT); if ($category_id == NULL || $category_id == FALSE || $product_id == NULL || $product_id == FALSE) { $error = "Missing or incorrect product id or category id."; include '../errors/error.php'; } else { delete_product($product_id); header("Location: .?category_id={$category_id}"); } } else { if ($action == 'show_add_form') { $categories = get_categories(); include 'product_add.php'; } else { if ($action == 'add_product') { $category_id = filter_input(INPUT_POST, 'category_id', FILTER_VALIDATE_INT); $code = filter_input(INPUT_POST, 'code'); $name = filter_input(INPUT_POST, 'name'); $price = filter_input(INPUT_POST, 'price'); if ($category_id == NULL || $category_id == FALSE || $code == NULL || $name == NULL || $price == NULL || $price == FALSE) { $error = "Invalid product data. Check all fields and try again."; include '../errors/error.php'; } else { add_product($category_id, $code, $name, $price); header("Location: .?category_id={$category_id}"); } } } } }
} else if($result == 2){ header("location:index.php?page=account"); } } require "templates/change-password.php"; } else{ require "templates/account-page.php"; } } else if($page == 'admin' && isset($_SESSION['admin']) && $_SESSION['admin'] == true && isset($_GET['action'])){ if($_GET['action'] == 'add_product'){ if(isset($_POST['name'])){ add_product($_POST['name'], $_POST['contents'], $_POST['amount'], $_POST['nutriments'], $_POST['allergens'], $_POST['category'], $_POST['price'], $_POST['comparement_price'], $_POST['comparement_type']); } require "templates/admin/add-product.php"; } else if($_GET['action'] == 'add_category'){ if(isset($_POST['name'])){ add_category($_POST['name']); } require "templates/admin/add-category.php"; } else if($_GET['action'] == 'edit_category'){ if(isset($_POST['name']) && isset($_POST['id'])){ edit_category($_POST['name'], $_POST['id']); }
<?php include 'config.php'; /** Switch Case to Get Action from controller **/ switch ($_GET['action']) { case 'add_product': add_product(); break; case 'get_product': get_product(); break; case 'edit_product': edit_product(); break; case 'delete_product': delete_product(); break; case 'update_product': update_product(); break; } /** Function to Add Product **/ function add_product() { $data = json_decode(file_get_contents("php://input")); $prod_name = $data->prod_name; $prod_desc = $data->prod_desc; $prod_price = $data->prod_price; $prod_quantity = $data->prod_quantity; print_r($data); $qry = 'INSERT INTO product (prod_name,prod_desc,prod_price,prod_quantity) values ("' . $prod_name . '","' . $prod_desc . '",' . $prod_price . ',' . $prod_quantity . ')';
if ($product['code'] == '') { $product['code'] = replace_text_for_utf8($this->input->post('name')); // Have barcode? for ($i = is_product_code($product['code']); $i > 0; $i++) { $product['code'] = replace_text_for_utf8($this->input->post('name')) . '-' . $i; $i = is_product_code($product['code']); } } else { // Have barcode? if (is_product_code($product['code'])) { alertbox('alert-danger', get_lang('This barcode is found in the database. Used for another product.')); $continue = false; } } if ($continue) { $product_id = add_product($product); if ($product_id > 0) { alertbox('alert-success', get_lang('Operation is Successful'), ''); $log['date'] = $this->input->post('log_time'); $log['type'] = 'product'; $log['title'] = get_lang('Product'); $log['description'] = get_lang('Created a new product line card.'); $log['other_id'] = 'product:' . $product_id; add_log($log); } else { alertbox('alert-danger', get_lang('Error!')); } } } } ?>