Php 在线购物车的顶级商品不会被删除吗?
使用php和mysql构建一个在线商店,购物车会话中的项目都会很好地删除,除了最上面的项目。有什么想法吗? 从购物车中删除的代码:Php 在线购物车的顶级商品不会被删除吗?,php,session,Php,Session,使用php和mysql构建一个在线商店,购物车会话中的项目都会很好地删除,除了最上面的项目。有什么想法吗? 从购物车中删除的代码: <?php session_start(); $items = $_SESSION['cart']; $cartitems = explode(",", $items); if(isset($_GET['remove']) && !empty($_GET['remove'])){ $delite
<?php
session_start();
$items = $_SESSION['cart'];
$cartitems = explode(",", $items);
if(isset($_GET['remove']) && !empty($_GET['remove'])){
$delitem = $_GET['remove'];
unset($cartitems[$delitem]);
$itemids = implode(",", $cartitems);
$_SESSION['cart'] = $itemids;
}
header('location:cart.php');
?>
我很感激能得到的任何帮助 将您的
$\u会话['cart']
转换为一个数组要比将多个ID用分隔符连接在一个字符串中容易得多。然后可以使用array\u filter()
和array\u search()
然后,要访问您的购物车,您可以使用:
function getItemsFromCart($callback) {
if(!is_callable($callback)) return false; # Ensure it is a Closure
foreach($_SESSION['cart'] as $product) call_user_func($callback, (object) $product); # Pass every array as an object to the function
}
可以这样使用:
getItemsFromCart(function($product) {
# $product will be used for every product inside the cart with ->id and ->quantity
# Recommend making this a static call to get a connection rather than opening multiple - just demonstration purposes.
$stmt = (new PDO('dsn', 'user', 'pass', [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
PDO::ATTR_EMULATE_PREPARES => false
]))->Prepare('SELECT cost FROM myProductTable WHERE productId = ? LIMIT 1');
$stmt->execute(array((int) $product->id));
$cost = ((object) $stmt->fetch())->cost * (int) $product->quantity; # Here is your cost :)
});
和
单个与是按位的;您想要&&
并且觉得这可能是一个打字错误问题。@FunkFortyNiner我更正为“&&”而不是“&”,但不幸的是仍然无法解决问题,但我感谢您的更正。在会话中以数组形式存储项不是更容易吗?然后使用array\u filter()
循环使用更新的数组重置会话?这非常有用,谢谢。:-)我知道我可能没有使用最好的方法来实现这一点,这更有意义。您可能必须在removietemfromcart()
的基础上进行构建,这样您就可以减少数量,而不是删除整个产品,但这完全取决于您。如果您有任何问题、疑问或顾虑,或者您被卡住了,只需发表评论,我将获得一个SO聊天室供我们在中讨论。更新后显示getItemsFromCart()中的SQL用法示例。
function getItemsFromCart($callback) {
if(!is_callable($callback)) return false; # Ensure it is a Closure
foreach($_SESSION['cart'] as $product) call_user_func($callback, (object) $product); # Pass every array as an object to the function
}
getItemsFromCart(function($product) {
# $product will be used for every product inside the cart with ->id and ->quantity
# Recommend making this a static call to get a connection rather than opening multiple - just demonstration purposes.
$stmt = (new PDO('dsn', 'user', 'pass', [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
PDO::ATTR_EMULATE_PREPARES => false
]))->Prepare('SELECT cost FROM myProductTable WHERE productId = ? LIMIT 1');
$stmt->execute(array((int) $product->id));
$cost = ((object) $stmt->fetch())->cost * (int) $product->quantity; # Here is your cost :)
});