2017-07-26 80 views
-3

車項目的最大數量這是我添加項目到購物車php腳本:

session_start(); 
 
require_once("dbcontroller.php"); 
 
$db_handle = new DBController(); 
 

 
switch($_GET['action']) { 
 
case 'add': 
 
$productByCode = $db_handle->runQuery("SELECT item, brand, price, catalog FROM products WHERE catalog='".$_GET['catalog']."'"); 
 
$itemArray = array($productByCode[0][‘catalog']=>array(
 
    'item'=>$productByCode[0]['item'], 
 
    'brand'=>$productByCode[0]['brand'], 
 
    'price'=>$productByCode[0]['price'], 
 
    'catalog'=>$productByCode[0]['catalog'])); 
 

 
if(!empty($_SESSION['cart_item'])) { 
 
if(!in_array($productByCode[0]['catalog'],($_SESSION['cart_item']))) { 
 
$_SESSION['cart_item'] += $itemArray; 
 
} 
 
} 
 
else { 
 
$_SESSION['cart_item'] = $itemArray; 
 
}

我想車項目的最大數量限制爲20 ,這意味着即使用戶點擊添加按鈕時沒有在$ _session中找到新項目,購物車項目已達到20,新項目將不會再添加。有沒有辦法做到這一點?請幫助。提前致謝。

+1

首先,請停止與任何亂搞那甚至遠遠與任何購物功能有關,只要你還沒有學會如何應對SQL注入...... – CBroe

+0

其次,你究竟是什麼意思 - 20個不同數量的數量不同(後者無關緊要),或總數20的時候訂購的數量加起來? – CBroe

+0

20個不同數量的不同數量,酷男,我只是在這裏學習。即使那個腳本我從人的教程 –

回答

1

你有幾個問題。 in_array不會按照您的方式工作,因爲它比較了數組值而不是密鑰。所以使用array_keys來測試。您也可以使用isset($_SESSION['cart_item'][$productByCode[0]['catalog'])而不是in_array(array_keys(...))來獲得相同的效果。

我更新了添加代碼以使用array_merge,因此很清楚新購物車項目正在發生什麼。

你也應該參數的SQL查詢,以避免SQL注入的問題(我沒有在你的代碼更正此)

session_start(); 
 
require_once("dbcontroller.php"); 
 
$db_handle = new DBController(); 
 

 
switch($_GET['action']) { 
 
case 'add': 
 
$productByCode = $db_handle->runQuery("SELECT item, brand, price, catalog FROM products WHERE catalog='".$_GET['catalog']."'"); 
 
$itemArray = array($productByCode[0][‘catalog']=>array(
 
    'item'=>$productByCode[0]['item'], 
 
    'brand'=>$productByCode[0]['brand'], 
 
    'price'=>$productByCode[0]['price'], 
 
    'catalog'=>$productByCode[0]['catalog'])); 
 

 
if(!empty($_SESSION['cart_item'])) { 
 
    if(count($_SESSION['cart_item']) < 20 && !in_array($productByCode[0]['catalog'],array_keys($_SESSION['cart_item']))) { 
 
     $_SESSION['cart_item'] = array_merge($_SESSION['cart_item'], $itemArray); 
 
    } 
 
} 
 
else { 
 
    $_SESSION['cart_item'] = $itemArray; 
 
}

+0

計數($ _ SESSION ['cart_item'])<20作爲我想要的。感謝這個想法。 –