2015-04-07 22 views
-5

我是PHP新手,我正在为我的网站制作购物车。我想增加更改同一页面中项目数量的可能性。当我点击它时显示项目。我只想要如何更改该代码中的数量?

<?php 
session_start(); 
require 'connect.php'; 
require 'item.php'; 

if(isset($_GET['itemid'])){ 
$query = 'select * from items where itemid='.$_GET['itemid']; 
$result = mysqli_query($mysqli,$query); 
$items = mysqli_fetch_object($result); 
$item = new Item(); 
$item->id = $items->itemid; 
$item->name = $items->itemname; 
$item->price = $items->price; 
$item->quantity = 1; 
// Check item is existing in cart 
$index = -1; 
$cart = unserialize(serialize($_SESSION['cart'])); 
for($i=0; $i<count($cart);$i++) 
    if($cart[$i]->id==$_GET['itemid']) 
    { 
     $index = $i; 
     break; 
    } 
if($index==-1) 
    $_SESSION['cart'][]= $item; 
else{ 
    $cart[$index]->quantity++; 
    $_SESSION['cart'] = $cart; 
} 

} 
//Delete item in cart 
if(isset($_GET['index'])){ 
$cart = unserialize(serialize($_SESSION['cart'])); 
unset($cart[$_GET['index']]); 
$cart = array_values($cart); 
$_SESSION['cart'] = $cart; 
} 
?> 
<table cellpadding="2" cellspacing="2" border="1" > 
<tr> 
<th>option</th> 
<th>Id</th> 
<th>Name</th> 
<th>Price</th> 
<th>Quantity</th> 
<th>Sub Total</th> 
</tr> 
<?php 
$cart = unserialize(serialize($_SESSION['cart'])); 
$s = 0; 
for($i=0; $i<count($cart);$i++){ 
$s += $cart[$i]->price* $cart[$i]->quantity; 
?> 

<tr> 
<td><a href="cart.php?index=<?php echo $index; ?>" onclick="return confirm('Are you sure?')">Delete</a></td> 
<td><?php echo $cart[$i]->id; ?></td> 
<td><?php echo $cart[$i]->name; ?></td> 
<td><?php echo $cart[$i]->price; ?></td> 
<td><?php echo $cart[$i]->quantity; ?></td> 
<td><?php echo $cart[$i]->price* $cart[$i]->quantity; ?></td> 
</tr> 
<?php 
$index++; 
} 
?> 
<tr> 
<td colspan="5" align="right">Sum</td> 
<td align="left" ><?php echo $s; ?></td> 
</tr> 
</table> 
<br> 
<a href="newfile.php">Continue Shopping</a> 
+0

您是否制作真正的购物车或者您只是在学习php?因为这样你的代码就可以打开SQL注入。 $ _GET ['something']直接传递到SQL查询是不是在PHP世界没有...看看这个:http://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection -in -php – Whirlwind

+4

***“请快速帮忙”*** - 我们不在工资单上。 –

+0

@ Fred-ii-想要快点,但还没有费心检查半小时。 –

回答

1

一个简单而快速的解决方法是在“数量”表单中添加一个字段,并在php中传递一个$ _GET变量。

$item->quantity = $_GET['quantity']; 
+3

顺便说一句,不要因downvote而气馁。人们无时无刻都在做这件事。你的答案比downvoter给出的答案更有用。 – castis

+0

^我同意@castis。另外,这不是我的失望。我为一,总是会给一个downvote一个解释/评论。 –

+2

感谢您的关注和友好的建议。 –

相关问题