Как создать интернет-корзину покупок в php

Я создаю корзину покупок, в которой есть четыре кнопки, чтобы продолжить покупки, очистить корзину, обновить корзину и сделать заказ. Мне приходится сталкиваться с проблемами с сеансами, например, когда я нажимаю кнопку чистой тележки, она показывает

undefined index cart 

но тележка приходит из сеанса, и когда я нажимаю кнопку чистой тележки

 it unsets the session of cart 

так где я делаю это неправильно? может ли кто-нибудь помочь? вот мой код

 <?php include("includes/db.php"); include("includes/functions.php"); if($_REQUEST['command']=='delete' && $_REQUEST['pid']>0){ remove_product($_REQUEST['pid']); } else if($_REQUEST['command']=='clear'){ unset($_SESSION['cart']); } else if($_REQUEST['command']=='update'){ $max=count($_SESSION['cart']); for($i=0;$i<$max;$i++){ $pid=$_SESSION['cart'][$i]['productid']; $q=intval($_REQUEST['product'.$pid]); if($q>0 && $q<=999){ $_SESSION['cart'][$i]['qty']=$q; } else{ $msg='Some proudcts not updated!, quantity must be a number between 1 and 999'; } } } ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Shopping Cart</title> <script language="javascript"> function del(pid){ if(confirm('Do you really mean to delete this item')){ document.form1.pid.value=pid; document.form1.command.value='delete'; document.form1.submit(); } } function clear_cart(){ if(confirm('This will empty your shopping cart, continue?')){ document.form1.command.value='clear'; document.form1.submit(); } } function update_cart(){ document.form1.command.value='update'; document.form1.submit(); } </script> </head> <body> <form name="form1" method="post"> <input type="hidden" name="pid" /> <input type="hidden" name="command" /> <div style="margin:0px auto; width:600px;" > <div style="padding-bottom:10px"> <h1 align="center">Your Shopping Cart</h1> <input type="button" value="Continue Shopping" onclick="window.location='products.php'" /> </div> <div style="color:#F00"><?php echo'' ;?></div> <table border="0" cellpadding="5px" cellspacing="1px" style="font-family:Verdana, Geneva, sans-serif; font-size:11px; background-color:#E1E1E1" width="100%"> <?php if(is_array($_SESSION['cart'])){ echo '<tr bgcolor="#FFFFFF" style="font-weight:bold"><td>Serial</td><td>Name</td><td>Price</td><td>Qty</td><td>Amount</td><td>Options</td></tr>'; $max=count($_SESSION['cart']); for($i=0;$i<$max;$i++){ $pid=$_SESSION['cart'][$i]['productid']; $q=$_SESSION['cart'][$i]['qty']; $pname=get_product_name($pid); if($q==0) continue; ?> <tr bgcolor="#FFFFFF"><td><?php echo $i+1?></td><td><?php echo $pname?></td> <td>$ <?php echo get_price($pid)?></td> <td><input type="text" name="product<?php echo $pid?>" value="<?php echo $q?>" maxlength="3" size="2" /></td> <td>$ <?php echo get_price($pid)*$q?></td> <td><a href="javascript:del(<?php echo $pid?>)">Remove</a></td></tr> <?php } ?> <tr><td><b>Order Total: $<?php echo get_order_total()?></b></td><td colspan="5" align="right"><input type="button" value="Clear Cart" onclick="clear_cart()"><input type="button" value="Update Cart" onclick="update_cart()"><input type="button" value="Place Order" onclick="window.location='billing.php'"></td></tr> <?php } else{ echo "<tr bgColor='#FFFFFF'><td>There are no items in your shopping cart!</td>"; } ?> </table> </div> </form> </body> </html> в <?php include("includes/db.php"); include("includes/functions.php"); if($_REQUEST['command']=='delete' && $_REQUEST['pid']>0){ remove_product($_REQUEST['pid']); } else if($_REQUEST['command']=='clear'){ unset($_SESSION['cart']); } else if($_REQUEST['command']=='update'){ $max=count($_SESSION['cart']); for($i=0;$i<$max;$i++){ $pid=$_SESSION['cart'][$i]['productid']; $q=intval($_REQUEST['product'.$pid]); if($q>0 && $q<=999){ $_SESSION['cart'][$i]['qty']=$q; } else{ $msg='Some proudcts not updated!, quantity must be a number between 1 and 999'; } } } ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Shopping Cart</title> <script language="javascript"> function del(pid){ if(confirm('Do you really mean to delete this item')){ document.form1.pid.value=pid; document.form1.command.value='delete'; document.form1.submit(); } } function clear_cart(){ if(confirm('This will empty your shopping cart, continue?')){ document.form1.command.value='clear'; document.form1.submit(); } } function update_cart(){ document.form1.command.value='update'; document.form1.submit(); } </script> </head> <body> <form name="form1" method="post"> <input type="hidden" name="pid" /> <input type="hidden" name="command" /> <div style="margin:0px auto; width:600px;" > <div style="padding-bottom:10px"> <h1 align="center">Your Shopping Cart</h1> <input type="button" value="Continue Shopping" onclick="window.location='products.php'" /> </div> <div style="color:#F00"><?php echo'' ;?></div> <table border="0" cellpadding="5px" cellspacing="1px" style="font-family:Verdana, Geneva, sans-serif; font-size:11px; background-color:#E1E1E1" width="100%"> <?php if(is_array($_SESSION['cart'])){ echo '<tr bgcolor="#FFFFFF" style="font-weight:bold"><td>Serial</td><td>Name</td><td>Price</td><td>Qty</td><td>Amount</td><td>Options</td></tr>'; $max=count($_SESSION['cart']); for($i=0;$i<$max;$i++){ $pid=$_SESSION['cart'][$i]['productid']; $q=$_SESSION['cart'][$i]['qty']; $pname=get_product_name($pid); if($q==0) continue; ?> <tr bgcolor="#FFFFFF"><td><?php echo $i+1?></td><td><?php echo $pname?></td> <td>$ <?php echo get_price($pid)?></td> <td><input type="text" name="product<?php echo $pid?>" value="<?php echo $q?>" maxlength="3" size="2" /></td> <td>$ <?php echo get_price($pid)*$q?></td> <td><a href="javascript:del(<?php echo $pid?>)">Remove</a></td></tr> <?php } ?> <tr><td><b>Order Total: $<?php echo get_order_total()?></b></td><td colspan="5" align="right"><input type="button" value="Clear Cart" onclick="clear_cart()"><input type="button" value="Update Cart" onclick="update_cart()"><input type="button" value="Place Order" onclick="window.location='billing.php'"></td></tr> <?php } else{ echo "<tr bgColor='#FFFFFF'><td>There are no items in your shopping cart!</td>"; } ?> </table> </div> </form> </body> </html> в <?php include("includes/db.php"); include("includes/functions.php"); if($_REQUEST['command']=='delete' && $_REQUEST['pid']>0){ remove_product($_REQUEST['pid']); } else if($_REQUEST['command']=='clear'){ unset($_SESSION['cart']); } else if($_REQUEST['command']=='update'){ $max=count($_SESSION['cart']); for($i=0;$i<$max;$i++){ $pid=$_SESSION['cart'][$i]['productid']; $q=intval($_REQUEST['product'.$pid]); if($q>0 && $q<=999){ $_SESSION['cart'][$i]['qty']=$q; } else{ $msg='Some proudcts not updated!, quantity must be a number between 1 and 999'; } } } ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Shopping Cart</title> <script language="javascript"> function del(pid){ if(confirm('Do you really mean to delete this item')){ document.form1.pid.value=pid; document.form1.command.value='delete'; document.form1.submit(); } } function clear_cart(){ if(confirm('This will empty your shopping cart, continue?')){ document.form1.command.value='clear'; document.form1.submit(); } } function update_cart(){ document.form1.command.value='update'; document.form1.submit(); } </script> </head> <body> <form name="form1" method="post"> <input type="hidden" name="pid" /> <input type="hidden" name="command" /> <div style="margin:0px auto; width:600px;" > <div style="padding-bottom:10px"> <h1 align="center">Your Shopping Cart</h1> <input type="button" value="Continue Shopping" onclick="window.location='products.php'" /> </div> <div style="color:#F00"><?php echo'' ;?></div> <table border="0" cellpadding="5px" cellspacing="1px" style="font-family:Verdana, Geneva, sans-serif; font-size:11px; background-color:#E1E1E1" width="100%"> <?php if(is_array($_SESSION['cart'])){ echo '<tr bgcolor="#FFFFFF" style="font-weight:bold"><td>Serial</td><td>Name</td><td>Price</td><td>Qty</td><td>Amount</td><td>Options</td></tr>'; $max=count($_SESSION['cart']); for($i=0;$i<$max;$i++){ $pid=$_SESSION['cart'][$i]['productid']; $q=$_SESSION['cart'][$i]['qty']; $pname=get_product_name($pid); if($q==0) continue; ?> <tr bgcolor="#FFFFFF"><td><?php echo $i+1?></td><td><?php echo $pname?></td> <td>$ <?php echo get_price($pid)?></td> <td><input type="text" name="product<?php echo $pid?>" value="<?php echo $q?>" maxlength="3" size="2" /></td> <td>$ <?php echo get_price($pid)*$q?></td> <td><a href="javascript:del(<?php echo $pid?>)">Remove</a></td></tr> <?php } ?> <tr><td><b>Order Total: $<?php echo get_order_total()?></b></td><td colspan="5" align="right"><input type="button" value="Clear Cart" onclick="clear_cart()"><input type="button" value="Update Cart" onclick="update_cart()"><input type="button" value="Place Order" onclick="window.location='billing.php'"></td></tr> <?php } else{ echo "<tr bgColor='#FFFFFF'><td>There are no items in your shopping cart!</td>"; } ?> </table> </div> </form> </body> </html> с <?php include("includes/db.php"); include("includes/functions.php"); if($_REQUEST['command']=='delete' && $_REQUEST['pid']>0){ remove_product($_REQUEST['pid']); } else if($_REQUEST['command']=='clear'){ unset($_SESSION['cart']); } else if($_REQUEST['command']=='update'){ $max=count($_SESSION['cart']); for($i=0;$i<$max;$i++){ $pid=$_SESSION['cart'][$i]['productid']; $q=intval($_REQUEST['product'.$pid]); if($q>0 && $q<=999){ $_SESSION['cart'][$i]['qty']=$q; } else{ $msg='Some proudcts not updated!, quantity must be a number between 1 and 999'; } } } ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Shopping Cart</title> <script language="javascript"> function del(pid){ if(confirm('Do you really mean to delete this item')){ document.form1.pid.value=pid; document.form1.command.value='delete'; document.form1.submit(); } } function clear_cart(){ if(confirm('This will empty your shopping cart, continue?')){ document.form1.command.value='clear'; document.form1.submit(); } } function update_cart(){ document.form1.command.value='update'; document.form1.submit(); } </script> </head> <body> <form name="form1" method="post"> <input type="hidden" name="pid" /> <input type="hidden" name="command" /> <div style="margin:0px auto; width:600px;" > <div style="padding-bottom:10px"> <h1 align="center">Your Shopping Cart</h1> <input type="button" value="Continue Shopping" onclick="window.location='products.php'" /> </div> <div style="color:#F00"><?php echo'' ;?></div> <table border="0" cellpadding="5px" cellspacing="1px" style="font-family:Verdana, Geneva, sans-serif; font-size:11px; background-color:#E1E1E1" width="100%"> <?php if(is_array($_SESSION['cart'])){ echo '<tr bgcolor="#FFFFFF" style="font-weight:bold"><td>Serial</td><td>Name</td><td>Price</td><td>Qty</td><td>Amount</td><td>Options</td></tr>'; $max=count($_SESSION['cart']); for($i=0;$i<$max;$i++){ $pid=$_SESSION['cart'][$i]['productid']; $q=$_SESSION['cart'][$i]['qty']; $pname=get_product_name($pid); if($q==0) continue; ?> <tr bgcolor="#FFFFFF"><td><?php echo $i+1?></td><td><?php echo $pname?></td> <td>$ <?php echo get_price($pid)?></td> <td><input type="text" name="product<?php echo $pid?>" value="<?php echo $q?>" maxlength="3" size="2" /></td> <td>$ <?php echo get_price($pid)*$q?></td> <td><a href="javascript:del(<?php echo $pid?>)">Remove</a></td></tr> <?php } ?> <tr><td><b>Order Total: $<?php echo get_order_total()?></b></td><td colspan="5" align="right"><input type="button" value="Clear Cart" onclick="clear_cart()"><input type="button" value="Update Cart" onclick="update_cart()"><input type="button" value="Place Order" onclick="window.location='billing.php'"></td></tr> <?php } else{ echo "<tr bgColor='#FFFFFF'><td>There are no items in your shopping cart!</td>"; } ?> </table> </div> </form> </body> </html> - <?php include("includes/db.php"); include("includes/functions.php"); if($_REQUEST['command']=='delete' && $_REQUEST['pid']>0){ remove_product($_REQUEST['pid']); } else if($_REQUEST['command']=='clear'){ unset($_SESSION['cart']); } else if($_REQUEST['command']=='update'){ $max=count($_SESSION['cart']); for($i=0;$i<$max;$i++){ $pid=$_SESSION['cart'][$i]['productid']; $q=intval($_REQUEST['product'.$pid]); if($q>0 && $q<=999){ $_SESSION['cart'][$i]['qty']=$q; } else{ $msg='Some proudcts not updated!, quantity must be a number between 1 and 999'; } } } ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Shopping Cart</title> <script language="javascript"> function del(pid){ if(confirm('Do you really mean to delete this item')){ document.form1.pid.value=pid; document.form1.command.value='delete'; document.form1.submit(); } } function clear_cart(){ if(confirm('This will empty your shopping cart, continue?')){ document.form1.command.value='clear'; document.form1.submit(); } } function update_cart(){ document.form1.command.value='update'; document.form1.submit(); } </script> </head> <body> <form name="form1" method="post"> <input type="hidden" name="pid" /> <input type="hidden" name="command" /> <div style="margin:0px auto; width:600px;" > <div style="padding-bottom:10px"> <h1 align="center">Your Shopping Cart</h1> <input type="button" value="Continue Shopping" onclick="window.location='products.php'" /> </div> <div style="color:#F00"><?php echo'' ;?></div> <table border="0" cellpadding="5px" cellspacing="1px" style="font-family:Verdana, Geneva, sans-serif; font-size:11px; background-color:#E1E1E1" width="100%"> <?php if(is_array($_SESSION['cart'])){ echo '<tr bgcolor="#FFFFFF" style="font-weight:bold"><td>Serial</td><td>Name</td><td>Price</td><td>Qty</td><td>Amount</td><td>Options</td></tr>'; $max=count($_SESSION['cart']); for($i=0;$i<$max;$i++){ $pid=$_SESSION['cart'][$i]['productid']; $q=$_SESSION['cart'][$i]['qty']; $pname=get_product_name($pid); if($q==0) continue; ?> <tr bgcolor="#FFFFFF"><td><?php echo $i+1?></td><td><?php echo $pname?></td> <td>$ <?php echo get_price($pid)?></td> <td><input type="text" name="product<?php echo $pid?>" value="<?php echo $q?>" maxlength="3" size="2" /></td> <td>$ <?php echo get_price($pid)*$q?></td> <td><a href="javascript:del(<?php echo $pid?>)">Remove</a></td></tr> <?php } ?> <tr><td><b>Order Total: $<?php echo get_order_total()?></b></td><td colspan="5" align="right"><input type="button" value="Clear Cart" onclick="clear_cart()"><input type="button" value="Update Cart" onclick="update_cart()"><input type="button" value="Place Order" onclick="window.location='billing.php'"></td></tr> <?php } else{ echo "<tr bgColor='#FFFFFF'><td>There are no items in your shopping cart!</td>"; } ?> </table> </div> </form> </body> </html> - <?php include("includes/db.php"); include("includes/functions.php"); if($_REQUEST['command']=='delete' && $_REQUEST['pid']>0){ remove_product($_REQUEST['pid']); } else if($_REQUEST['command']=='clear'){ unset($_SESSION['cart']); } else if($_REQUEST['command']=='update'){ $max=count($_SESSION['cart']); for($i=0;$i<$max;$i++){ $pid=$_SESSION['cart'][$i]['productid']; $q=intval($_REQUEST['product'.$pid]); if($q>0 && $q<=999){ $_SESSION['cart'][$i]['qty']=$q; } else{ $msg='Some proudcts not updated!, quantity must be a number between 1 and 999'; } } } ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Shopping Cart</title> <script language="javascript"> function del(pid){ if(confirm('Do you really mean to delete this item')){ document.form1.pid.value=pid; document.form1.command.value='delete'; document.form1.submit(); } } function clear_cart(){ if(confirm('This will empty your shopping cart, continue?')){ document.form1.command.value='clear'; document.form1.submit(); } } function update_cart(){ document.form1.command.value='update'; document.form1.submit(); } </script> </head> <body> <form name="form1" method="post"> <input type="hidden" name="pid" /> <input type="hidden" name="command" /> <div style="margin:0px auto; width:600px;" > <div style="padding-bottom:10px"> <h1 align="center">Your Shopping Cart</h1> <input type="button" value="Continue Shopping" onclick="window.location='products.php'" /> </div> <div style="color:#F00"><?php echo'' ;?></div> <table border="0" cellpadding="5px" cellspacing="1px" style="font-family:Verdana, Geneva, sans-serif; font-size:11px; background-color:#E1E1E1" width="100%"> <?php if(is_array($_SESSION['cart'])){ echo '<tr bgcolor="#FFFFFF" style="font-weight:bold"><td>Serial</td><td>Name</td><td>Price</td><td>Qty</td><td>Amount</td><td>Options</td></tr>'; $max=count($_SESSION['cart']); for($i=0;$i<$max;$i++){ $pid=$_SESSION['cart'][$i]['productid']; $q=$_SESSION['cart'][$i]['qty']; $pname=get_product_name($pid); if($q==0) continue; ?> <tr bgcolor="#FFFFFF"><td><?php echo $i+1?></td><td><?php echo $pname?></td> <td>$ <?php echo get_price($pid)?></td> <td><input type="text" name="product<?php echo $pid?>" value="<?php echo $q?>" maxlength="3" size="2" /></td> <td>$ <?php echo get_price($pid)*$q?></td> <td><a href="javascript:del(<?php echo $pid?>)">Remove</a></td></tr> <?php } ?> <tr><td><b>Order Total: $<?php echo get_order_total()?></b></td><td colspan="5" align="right"><input type="button" value="Clear Cart" onclick="clear_cart()"><input type="button" value="Update Cart" onclick="update_cart()"><input type="button" value="Place Order" onclick="window.location='billing.php'"></td></tr> <?php } else{ echo "<tr bgColor='#FFFFFF'><td>There are no items in your shopping cart!</td>"; } ?> </table> </div> </form> </body> </html> 

Related of "Как создать интернет-корзину покупок в php"

Если вы еще не начали заполнять свою корзину, элемент не будет определен. При работе с элементами массива всегда лучше добавить дополнительный тест array_key_exists (). Однако в вашем случае проблема больше связана с тем, как вы обрабатываете свой массив в целом.

PHP очень прощает, поэтому вы должны применять свои собственные дисциплины по тому, как вы код. Одна часть очень хорошей практики, которую стоит привыкнуть, – явно инициализировать ваши переменные, прежде чем вы начнете их использовать.

 // somewhere near the top of your code $_SESSION['cart'] = array_key_exists('cart', $_SESSION)?$_SESSION['cart']:array(); 

и не отключайте его в ясном тесте … просто верните его в пустой массив.

 else if($_REQUEST['command']=='clear'){ $_SESSION['cart'] = array(); } 

здесь Простой учебник по покупкам в PHP

 $product_id = $_GET['id']; //the product id from the URL $action = $_GET['action']; //the action from the URL //if there is an product_id and that product_id doesn't exist display an error message if($product_id && !productExists($product_id)) { die("Error. Product Doesn't Exist"); } switch($action) { //decide what to do case "add": $_SESSION['cart'][$product_id]++; //add one to the quantity of the product with id $product_id break; case "remove": $_SESSION['cart'][$product_id]--; //remove one from the quantity of the product with id $product_id if($_SESSION['cart'][$product_id] == 0) unset($_SESSION['cart'][$product_id]); //if the quantity is zero, remove it completely (using the 'unset' function) - otherwise is will show zero, then -1, -2 etc when the user keeps removing items. break; case "empty": unset($_SESSION['cart']); //unset the whole cart, ie empty the cart. break; } ?> с $product_id = $_GET['id']; //the product id from the URL $action = $_GET['action']; //the action from the URL //if there is an product_id and that product_id doesn't exist display an error message if($product_id && !productExists($product_id)) { die("Error. Product Doesn't Exist"); } switch($action) { //decide what to do case "add": $_SESSION['cart'][$product_id]++; //add one to the quantity of the product with id $product_id break; case "remove": $_SESSION['cart'][$product_id]--; //remove one from the quantity of the product with id $product_id if($_SESSION['cart'][$product_id] == 0) unset($_SESSION['cart'][$product_id]); //if the quantity is zero, remove it completely (using the 'unset' function) - otherwise is will show zero, then -1, -2 etc when the user keeps removing items. break; case "empty": unset($_SESSION['cart']); //unset the whole cart, ie empty the cart. break; } ?> 

отсюда

 switch($action) { //decide what to do case "add": $_SESSION['cart'][$product_id]++; //add one to the quantity of the product with id $product_id break; case "remove": $_SESSION['cart'][$product_id]--; //remove one from the quantity of the product with id $product_id if($_SESSION['cart'][$product_id] == 0) unset($_SESSION['cart'][$product_id]); //if the quantity is zero, remove it completely (using the 'unset' function) - otherwise is will show zero, then -1, -2 etc when the user keeps removing items. break; case "empty": unset($_SESSION['cart']); //unset the whole cart, ie empty the cart. break; с switch($action) { //decide what to do case "add": $_SESSION['cart'][$product_id]++; //add one to the quantity of the product with id $product_id break; case "remove": $_SESSION['cart'][$product_id]--; //remove one from the quantity of the product with id $product_id if($_SESSION['cart'][$product_id] == 0) unset($_SESSION['cart'][$product_id]); //if the quantity is zero, remove it completely (using the 'unset' function) - otherwise is will show zero, then -1, -2 etc when the user keeps removing items. break; case "empty": unset($_SESSION['cart']); //unset the whole cart, ie empty the cart. break;