Warning: Cannot use a scalar value as an array in /home/admin/public_html/forum/include/fm.class.php on line 757

Warning: Invalid argument supplied for foreach() in /home/admin/public_html/forum/include/fm.class.php on line 770

Warning: Invalid argument supplied for foreach() in /home/admin/public_html/forum/topic.php on line 737
Форумы портала PHP.SU :: подправить код , работа с сессиями

 PHP.SU

Программирование на PHP, MySQL и другие веб-технологии
PHP.SU Портал     На главную страницу форума Главная     Помощь Помощь     Поиск Поиск     Поиск Яндекс Поиск Яндекс     Вакансии  Пользователи Пользователи


 Страниц (1): [1]   

> Описание: имеется код покупательской корзины, добавил параметр prod_size а как сделать prod_size на сессии не пойму
bboyb-rock
Отправлено: 27 Января, 2011 - 11:09:23
Post Id


Частый гость


Покинул форум
Сообщений всего: 175
Дата рег-ции: Янв. 2011  
Откуда: Артемовск Украина Донецкая область


Помог: 0 раз(а)




Описание: имеется код покупательской корзины, добавил параметр prod_size сделал методом POST, теперь размер появился а вот если добавляеш несколько товаров в корзину остается только первый добавленный а остальные не видно но при удалении появляется один за одним, сумму считает. Как зделать так чтобы было видно все товары в корзине?
<?php


// shopping cart

//calculate shopping cart value

if (isset($_GET["shopping_cart"]) || isset($_POST["shopping_cart"]))
{
$prod_size = $_POST["product_size"];
if (isset($_GET["add2cart"]) && $_GET["add2cart"]>0) //add product to cart with productID=$add
{

$q = db_query("select in_stock from ".PRODUCTS_TABLE." where productID='".$_GET["add2cart"]."'") or die (db_error());
$is = db_fetch_row($q); $is = $is[0];

//$_SESSION[gids] contains product IDs
//$_SESSION[counts] contains product quantities ($_SESSION[counts][$i] corresponds to $_SESSION[gids][$i])
//$_SESSION[gids][$i] == 0 means $i-element is 'empty'
if (!isset($_SESSION["gids"]))
{
$_SESSION["gids"] = array();
$_SESSION["counts"] = array();

}
//check for current item in the current shopping cart content
$i=0;
while ($i<count($_SESSION["gids"]) && $_SESSION["gids"][$i] != $_GET["add2cart"]) $i++;
if ($i < count($_SESSION["gids"])) //increase current product's quantity
{
$_SESSION["counts"][$i]++;
}
else //no item - add it to $gids array
{
$_SESSION["gids"][] = $_GET["add2cart"];
$_SESSION["counts"][] = 1;
}

header("Location: index.php?shopping_cart=yes&prod_size=".$prod_size);

}


if (isset($_GET["remove"]) && $_GET["remove"] > 0) //remove from cart product with productID == $remove
{
$i=0;
while ($i<count($_SESSION["gids"]) && $_SESSION["gids"][$i] != $_GET["remove"]) $i++;
if ($i<count($_SESSION["gids"])) $_SESSION["gids"][$i] = 0;

header("Location: index.php?shopping_cart=yes");
}


if (isset($_POST["update"])) //update shopping cart content
{

foreach ($_POST as $key => $val)
if (strstr($key, "count_"))
{
//select product's in stock level
$q = db_query("select in_stock from ".PRODUCTS_TABLE." where productID='".str_replace("count_","",$key)."'") or die (db_error());
$is = db_fetch_row($q); $is = $is[0];

if ($val > 0)
{
for ($i=0; $i<count($_SESSION["gids"]); $i++)
{
if ($_SESSION["gids"][$i] == str_replace("count_","",$key))
{
$_SESSION["counts"][$i] = floor($val);
}
}
}
else //remove
{
$i=0;
while ($_SESSION["gids"][$i] != str_replace("count_","",$key) && $i<count($_SESSION["gids"])) $i++;
$_SESSION["gids"][$i] = 0;
}
}

header("Location: index.php?shopping_cart=yes");

}

if (isset($_GET["clear_cart"])) //completely clear shopping cart
{
//clear cart
if (isset($_SESSION["gids"])) unset($_SESSION["gids"]);
if (isset($_SESSION["counts"])) unset($_SESSION["counts"]);

header("Location: index.php?shopping_cart=yes");
}



//shopping cart items count
$c = 0;
if (isset($_SESSION["gids"]))
for ($j=0; $j<count($_SESSION["gids"]); $j++)
if ($_SESSION["gids"][$j]) $c += $_SESSION["counts"][$j];


//not empty?
if (isset($_SESSION["gids"]) && $c)
{
$k = 0; //total cart value

$products = array();



for ($i=0; $i<count($_SESSION["gids"]); $i++)
if ($_SESSION["gids"][$i])
{
$q = db_query("SELECT name, Price, product_code, size_one, size_two, size_three, size_four, size_five FROM ".PRODUCTS_TABLE." WHERE productID='".$_SESSION["gids"][$i]."'") or die (db_error());
if ($r = db_fetch_row($q))
{
$tmp = array("id"=>$_SESSION["gids"][$i], "name"=>$r[0], "quantity"=>$_SESSION["counts"][$i], "cost"=>show_price($_SESSION["counts"][$i]*$r[1]), "product_code"=>$r[2]);


$k += $_SESSION["counts"][$i]*$r[1];


$tmp["prod_size"] = $_GET["prod_size"];
for($i=3; $i<=7; $i++)
{
if($r[$i] != "")
{
$tmp["size_".$i] = $r[$i];
}
}



$products[] = $tmp;


}
}
//total...
$smarty->assign("cart_content", $products);
$smarty->assign("shopping_cart_value", $k);
$smarty->assign("cart_total", show_price($k));

}
else
{
$smarty->assign("cart_total", "");
}

$smarty->assign("main_content_template", "shopping_cart.tpl.html");


}
?>

(Отредактировано автором: 27 Января, 2011 - 23:22:51)

 
 Top
DiosPA
Отправлено: 27 Января, 2011 - 11:45:46
Post Id



Частый гость


Покинул форум
Сообщений всего: 180
Дата рег-ции: Янв. 2011  
Откуда: Россия


Помог: 2 раз(а)




если тебе надо просто параметр\значение передать в сессию то зарегистрируй её так
CODE (htmlphp):
скопировать код в буфер обмена
  1.  
  2. $_SESSION['prod_size] = $prod_size;
  3.  
 
 Top
Страниц (1): [1]
Сейчас эту тему просматривают: 0 (гостей: 0, зарегистрированных: 0)
« Напишите за меня, пожалуйста »


Все гости форума могут просматривать этот раздел.
Только зарегистрированные пользователи могут создавать новые темы в этом разделе.
Только зарегистрированные пользователи могут отвечать на сообщения в этом разделе.
 



Powered by PHP  Powered By MySQL  Powered by Nginx  Valid CSS  RSS

 
Powered by ExBB FM 1.0 RC1. InvisionExBB