【发布时间】:2015-04-07 23:10:45
【问题描述】:
我是 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>
【问题讨论】:
-
你是做真正的购物车还是只是在学习php?因为这样你的代码就会被 SQL 注入打开。 $_GET['something'] 直接传递给 SQL 查询在 PHP 世界中是不行的......看看这个:stackoverflow.com/questions/60174/…
-
“请快点帮忙” - 我们不在你的工资单上。
-
@Fred-ii- 想快点,但半小时都懒得回来查看。
-
@Dagon 他们一定也是仙人掌种植者。
-
@Dagon 只是我的意思不是那么快:D
标签: php mysqli shopping-cart