【发布时间】:2016-12-06 10:07:33
【问题描述】:
我正在为假设的租赁业务构建一个网站,并尝试在用户单击“添加到购物车”按钮时检查指定时间段内的可用库存。我在运行 SQL 查询时遇到了一些问题,主要是(我认为)因为我的 $product_id 变量是一个整数,但我要查询的列的形式是“item1”、“item2”等。
我尝试使用的逻辑是从表中可用的数字中减去所需的数量,在给定的时间跨度内取这些值中的最小值,然后检查该数字是否在任何时候低于零.
以下是相关代码:
switch ($action) {
case 'view':
$cart = cart_get_items();
break;
case 'add':
$product_id = filter_input(INPUT_GET, 'product_id', FILTER_VALIDATE_INT);
$quantity = filter_input(INPUT_GET, 'quantity');
$pickup = filter_input(INPUT_GET, 'pickup');
$return = filter_input(INPUT_GET, 'return');
// validate the quantity entry
if ($quantity === null) {
display_error('You must enter a quantity.');
} elseif (!is_valid_number($quantity, 1)) {
display_error('Quantity must be 1 or more.');
}
// check for available inventory
$query = "SELECT MIN((SELECT CONCAT('item',:product_id)) - :quantity) FROM running_inventory WHERE date BETWEEN :pickup AND :return";
$statement = $db->prepare($query);
$statement->bindValue(':product_id', $product_id);
$statement->bindValue(':quantity', $quantity);
$statement->bindValue(':pickup', $pickup);
$statement->bindValue(':return', $return);
$statement->execute();
$available = $statement->fetch();
$num_avail = $available[0];
var_dump($num_avail);
$statement->closeCursor();
if ($num_avail - $quantity >= 0) {
cart_add_item($product_id, $quantity);
} else {
display_error('The indicated quantity of stock is not available for your rental period.');
}
$cart = cart_get_items();
break;
这是 $available 的 var_dump:
array(2) { ["MIN((SELECT CONCAT('item','6')) - '3')"]=> string(2) "-3" [0]=> string(2) "-3" } string(2) "-3"
这显然只是从 0 中减去 $quantity,但我似乎无法准确找出问题所在。
【问题讨论】:
-
那么,有什么问题?
-
抱歉,我是 SO 新手,目前有点杂乱无章。我用 var_dump 编辑了帖子。
-
你还没有解释问题。您期望返回什么值?为什么要从字符串中减去一个数字?当然,这是行不通的。为什么对单个值使用 MIN 函数?这不会有任何作用。