Добавить в корзину Script - помощь в дизайне, пожалуйста - PullRequest
0 голосов
/ 27 августа 2009

Я пишу скрипт, который позволит пользователям размещать предметы в корзинах. Пока это очень сложно, и я хотел бы обсудить это с кем-то, чтобы увидеть, могут ли они предложить лучший дизайн или привести в порядок текущий дизайн. Вот код, который у меня есть, который не очень хорошо работает (т.е. есть ошибки, которые я еще не исправил) с комментариями, чтобы показать мои намерения:

<?php
session_start();
include_once("db_include.php5");
doDB();


if(!$_GET["productid"] || !$_GET["qty"]) {
//the user has entered the address directly into their address bar, send them away (if=1 to let me know where the script branched)
header("Location:index.php5?if=1");
exit();
}

**//do select query to verify item id is valid, in case they entered data into the query string or the item has been removed from db**
$check_sql = "SELECT * FROM aromaProducts1 WHERE id='".$_GET["productid"]."'";
$check_res = mysqli_query($mysqli, $check_sql) or die(mysqli_error($mysqli));

if(mysqli_num_rows($check_res) == 0) {
**//item doesn't exist, redirect user**
header("Location:index.php5?if=2");
exit();
} else if(mysqli_num_rows($check_res) != 0) {
**//item exists
//do select query to check for item id already in basket - if this item is already in the table associated with the user's session id (which will be added every time an item is), then we want to change the quantity only**
$duplicate_sql = "SELECT qty FROM sessionBasket WHERE product_id='".$_GET["productid"]."' AND usersessid='".$_SESSION["PHPSESSID"]."'";
$duplicate_res = mysqli_query($mysqli, $duplicate_sql) or die(mysqli_error($mysqli));

if(mysqli_num_rows($duplicate_res) != 0) {
**//item in basket - add another - fetch current quantity and add new quantity**
$basketInfo = mysqli_fetch_array($duplicate_res);
$currQty = $basket_info["qty"];
$add_sql = "UPDATE sessionBasket SET qty='".($_GET["qty"]+$currQty)."' WHERE usersessid='".$_SESSION["PHPSESSID"]."'AND product_id='".$_GET["productid"]."'";
$add_res = mysqli_query($mysqli, $add_sql) or die(mysqli_error($mysqli));

if($add_res !== TRUE) {
**//wasn't updated for some reason - this is where my script currently breaks**
header("Location:basketfailredirect.php5?error=add");
exit();
} else if($add_res === TRUE) {
**//was updated - send them away**
header("basket.php5?res=add");
exit();
}


} else if(mysqli_num_rows($duplicate_res) == 0) {
**//no existing items in basket, so we want to add the current item info associated with the user's id/session id**

**//fetch product id, passed in query string from the product info page**
$productid = $_GET["productid"];

**//sanitize possible inputs, if set - notes is a field added to the product info page for custom products, and we want to sanitize it if it's set - note that check_chars_mailto() is a function I have in the db_include file**
$notes = isset($_GET["notes"])?trim(mysqli_real_escape_string(check_chars_mailto($_GET["notes"]))):"";
**//if the user is logged in, their userid is stored in the session variable**
$userid = $_SESSION["userid"]?$_SESSION["userid"]:"";
**//not sure about the keep alive option - i.e. store basket contents even if the user doesnt register/sign in, but keeping the option there**
$alive = $_SESSION["alive"]?$_SESSION["alive"]:"no";


**//insert query**
$insert_sql = "INSERT INTO sessionBasket (userid, usersessid, date_added, keep_alive, product_id, qty, notes) VALUES (
'".$userid."',
'".$_SESSION["PHPSESSID"]."',
now(),
'".$alive."',
'".$productid."',
'".$_GET["qty"]."',
'".htmlspecialchars($notes)."')";
$insert_res = mysqli_query($mysqli, $insert_sql) or die(mysqli_error($mysqli));

if($insert_res === TRUE) {
**//success**
header("Location:basket.php5?res=add");
exit();
} else if($insert_res !== TRUE) {
**//fail**
header("Location:basketfailredirect.php5?error=add2");
exit();
}
}
}
?>

Это довольно сложно для меня - я хочу разрешить пустые поля, добавить идентификатор пользователя, если он доступен (чего нет в моем запросе ОБНОВЛЕНИЯ) ... Это миллион миль от хорошего дизайна, или как?

Кроме того, когда я пытаюсь добавить товары в корзину, я получаю сообщение об ошибке: внутренняя ошибка сервера 500. Я подозреваю, что это связано с неправильным кодированием, потому что мои результаты поиска и страницы просмотра продукта работают и используют один и та же база данных, что и этот скрипт.

1 Ответ

1 голос
/ 27 августа 2009

Вам следует рассмотреть возможность использования встроенного в PHP псевдообъектно-ориентированного стиля.

Возможно, вам следует также использовать PHP Framework, такой как Zend или CakePHP. Даже если вы не используете PHP-фреймворк, вы все равно сможете создавать свой код объектно-ориентированным способом с помощью объектов класса php и интерфейса.

Разделив этот код на классы и функции, вы значительно упростите вашу (и нашу) отладку, как сейчас, так и когда вы придете к редактированию кода в какой-то момент в будущем.

...