使用PHP $ _Session和NO SQL创建一页购物车 [英] Create a one page shopping cart using PHP $_Session and NO SQL
问题描述
我正在学习一些PHP,并且正在尝试创建一个所有页面的购物车。
我已经阅读并可以看到SQL基础系统的好处,但是我想首先学习基础知识。为此,我创建了一个多页的页面,其中包含关联数组中的产品以及提交给自己的表单。
我想要的要实现的目标是:
- 只能购买一次产品(购买按钮替换为删除按钮)
- 该项目及其成本将添加到下面的购物车中
- 用户可以将其从购物车中删除,也可以将其从项目列表中删除
- 总费用应根据要求进行更新。
- 结帐按钮将提交商品名称和费用
- 表格会自行发布,但不会需要任何SQL
我当前的问题是:
- 我一次不能购买多个物品,即购物车仅包含最后购买的物品
- 如果已购买了一件物品,是否购买了物品,我无法让它检查因此,将购买替换为删除
- 我无法在购物车中显示商品详情
- eckout按钮不会将任何详细信息传递给我的测试
再次,我还没有在寻找SQL解决方案,只是使用了纯PHP $ _ SESSION
和 $ _ POST
,并希望使用按钮而不是< a href add ?>
类型的链接。
感谢您冗长的阅读,代码如下:
<?php
session_start();
$ items =数组(
'A123'=>数组(
'name'=>'Item1',
'desc'=>'项目1描述...',
'价格'=> 1000
),
'B456'=>数组(
'name'=>'Item40' ,
'desc'=>'Item40 description ...',
'price'=> 2500
),
'Z999'=>数组(
'name'=>'Item999',
'desc'=>'Item999 description ...',
'price'=> 9999
)
);
if(!isset($ _SESSION ['cart'])){
$ _SESSION ['cart'] = array();
}
//如果(isset($ _POST [ buy])){
$ _SESSION ['cart'] = $ _POST;
}
//删除项目
else if(isset($ _POST ['delete'])){//单击删除按钮
未设置( $ _POST ['delete']); //
}
//空购物车
else if(isset($ _POST [ delete]])){//从购物车
中删除项目unset( $ _SESSION ['cart']);
}
?>
< form action ='<?php echo $ _SERVER ['PHP_SELF']; ?>'method ='post'>
<?php
foreach($ items as $ ino => $ item){
$ title = $ item ['name'];
$ desc = $ item [’desc’];
$ price = $ item ['price'];
echo< p> $ title< / p>;
echo< p> $ desc< / p>;
echo< p> \ $$ price< / p>;
if($ _SESSION ['cart'] == $ ino){
echo’< img src = carticon.png>’;
echo< p>< button type ='submit'name ='delete'value ='$ ino'> Remove< / button>< / p>;
}否则{
echo< button type ='submit'name ='buy'value ='$ ino'> Buy< / button>;
}
}
?>
< / form>
<?php
if(isset($ _SESSION [ cart])){
?>
< form action ='(省略的链接)'
target ='_ blank'method ='post'
enctype ='application / x-www-form-urlencoded' >
< table>
< tr>
< th> / th;
< Price< / th>
< th< / th;
< / tr>
<?php
$ total = 0;
foreach($ _SESSION [ cart] as $ i){
?>
< tr>
< td>
<?php echo($ _ SESSION [ cart]); ?> <!-商品名称->
< / td>
< td> price<?php echo($ _ SESSION [ price] [$ i]); ?>
<!-商品费用->
< / td>
< td><按钮类型='提交'名称='删除'值='$ ino'>删除< / button>
< / p>< / td>
< / tr>
<?php
$ total = + $ _SESSION [ amounts] [$ i];
}
$ _SESSION [ total] = $ total;
?>
< tr>
< td colspan = 2>总计:$<?php echo($ total); && lt; / td>
< td><输入类型=提交 value =结帐 />< / td>
< / tr>
< tr>
< td>< button type ='submit'name ='clear'>清除购物车< / button>< / td>
< / tr>
< / table>
< / form>
<?php}?>
您的脚本中需要解决一些问题,因此,我将它们分解为各个部分。
代码中也有很多安全错误检查,但作为纯粹的学习活动,我绕过了这些因素。
定义购物车
您将购物车定义为数组:
if(!isset($ _SESSION ['cart'])){
$ _SESSION ['cart' ] =数组();
}
但是,当您在购物车中添加商品时, >替换购物车:
//添加
if(isset($ _POST [ buy ])){{
$ _SESSION ['cart'] = $ _POST; //
}
要添加一个项目到购物车,则应该使用 $ cart [] = $ _POST
,但是,还需要考虑其他因素。
< h2>添加到购物车
$ cart [] = $ _POST
添加完整的当您只需要产品ID时,会将$ _POST
数据添加到购物车。正确的方法是:
//如果(isset($ _POST [ buy])),则添加
{
//检查商品是否尚未在购物车
中,如果(!in_array($ _ POST [ buy],$ _SESSION ['cart'])){
//添加新商品放入购物车
$ _SESSION ['购物车] [] = $ _POST [购买];
}
}
这将导致购物车存储多个值。例如, print_r($ _ SESSION ['cart'])
可能显示:
array(
0 =>'A123',
1 =>'B456'
);
此数组中的每个项目都是已添加到购物车中的项目。
从购物车中删除商品
现在, $ _ SESSION ['cart']的结构
已更改,从购物车中删除操作也需要更新。使用小的代码段,我们可以检查值是否存在于数组中,找到其键并将其删除。
//删除项目
else if(isset($ _POST ['delete'])){// a
//单击删除按钮
//如果(false!== $ key = array_search($ _ POST ['delete'],$ _SESSION ['cart'])){
未设置($ _SESSION ['cart'] [$ key]);
}
}
检查商品是否在购物车中
需要进一步更改代码才能支持新的数组结构。您可以使用 in_array
检查购物车数组中是否包含您的产品。
<?php
foreach ($ items as $ ino => $ item){
// ...简洁起见
//通过检查商品是否存在于购物车中来检查商品是否存在ID:
if(in_array($ ino,$ _SESSION ['cart'])){// $ ino对您的第一个产品来说是'a123'
echo< p>< button type ='submit'name ='delete'value ='$ ino'> Remove< / button>< / p>;
}否则{
echo< button type ='submit'name ='buy'value ='$ ino'> Buy< / button>;
}
}
?>
简化代码
在上面代码,我删除了一些代码。您正在执行以下操作:
$ title = $ item [’name’];
$ desc = $ item [’desc’];
$ price = $ item ['price'];
echo< p> $ title< / p>;
echo< p> $ desc< / p>;
echo< p> \ $$ price< / p>;
这可以简化为:
echo< p> $ item ['name']< / p>;
echo< p> $ item [’desc']< / p>;
echo< p> \ $$ item [’price']< / p>;
而不是将 $$
的两倍最后一行,我个人将使用:
echo'< p> $'。 number_format($ item [’name’])。 ‘< / p>’;
这使您可以更轻松地格式化数字的显示。或者,您可以使用 money_format
。
显示购物车
此代码存在一些问题。
- 您正尝试
将无法正常工作。您不能 echo
一个数组 - 您正在使用
foreach($ _SESSION [ cart]]作为$ i)
尝试使用<?php echo($ _ SESSION [ price] [$ i])显示值时不正确; ?>
- 您正在使用于
$ total
值的代码复杂化 - 由于将随机
< / p>
放入组合中
正确的显示方式是:
<?php
//设置默认的总计
$ total = 0;
foreach($ _SESSION ['cart'] as $ ino){
?>
< tr>
< td>
名称:<?php echo $ items [$ ino] [’name’]; ?>
< / td>
< td>
价格:<?php echo $ items [$ ino] [ price]; ?>
< / td>
< td>
< button type ='提交'name ='delete'value ='<?php echo $ ino; ?>’>删除< / button>
< / td>
< / tr>
<?php
$ total + = $ items [$ ino] [’price’];
} //结束foreach
吗?
总计:$<?php echo $ total; ?>
I am learning some PHP and I am trying to create a all in one page shopping cart.
I have read into and can see the benefits of a SQL bases system, but I want to learn the basics first. In doing so I have create a all-in-one page that contains the products in an associated array, as well as a form that submits to itself.
What I want to achieve is:
- A product can only be purchased once (buy button replaced with a remove button)
- The item and its cost are added to the cart below
- A user can either remove it from the cart, or the item list
- The total cost should be updated as required.
- The "checkout" button will submit item name and cost
- The form posts to itself and does not require any SQL
My current problem is:
- I cannot purchase more than one item at a time, i.e. the cart only contains the last purchased item
- I cannot get it to "check" if an item has been purchased and if so, replace the "buy" with "remove"
- I cannot display the item details in the cart
- The checkout button does not pass any details to my test
Again, I am not looking for a SQL solution yet, just a pure PHP using $_SESSION
and $_POST
and would like to use buttons instead of <a href add?>
type links.
Thanks for the lengthy read in advance here is the code:
<?php
session_start ();
$items = array (
'A123' => array (
'name' => 'Item1',
'desc' => 'Item 1 description...',
'price' => 1000
),
'B456' => array (
'name' => 'Item40',
'desc' => 'Item40 description...',
'price' => 2500
),
'Z999' => array (
'name' => 'Item999',
'desc' => 'Item999 description...',
'price' => 9999
)
);
if (! isset ( $_SESSION ['cart'] )) {
$_SESSION ['cart'] = array ();
}
// Add
if (isset ( $_POST ["buy"] )) {
$_SESSION ['cart'] = $_POST;
}
// Delete Item
else if (isset ( $_POST ['delete'] )) { // a remove button has been clicked
unset ( $_POST ['delete'] ); //
}
// Empty Cart
else if (isset ( $_POST ["delete"] )) { // remove item from cart
unset ( $_SESSION ['cart'] );
}
?>
<form action='<?php echo $_SERVER['PHP_SELF']; ?>' method='post'>
<?php
foreach ( $items as $ino => $item ) {
$title = $item ['name'];
$desc = $item ['desc'];
$price = $item ['price'];
echo " <p>$title</p>";
echo " <p>$desc</p>";
echo "<p>\$$price</p>";
if ($_SESSION ['cart'] == $ino) {
echo '<img src="carticon.png">';
echo "<p><button type='submit' name='delete' value='$ino'>Remove</button></p>";
} else {
echo "<button type='submit' name='buy' value='$ino'>Buy</button> ";
}
}
?>
</form>
<?php
if (isset ( $_SESSION ["cart"] )) {
?>
<form action='(omitted link)'
target='_blank' method='post'
enctype='application/x-www-form-urlencoded'>
<table>
<tr>
<th>Product</th>
<th>Price</th>
<th>Action</th>
</tr>
<?php
$total = 0;
foreach ( $_SESSION ["cart"] as $i ) {
?>
<tr>
<td>
<?php echo($_SESSION["cart"]); ?> <!--Item name-->
</td>
<td>price<?php echo($_SESSION["price"][$i] ); ?>
<!--Item cost-->
</td>
<td><button type='submit' name='delete' value='$ino'>Remove</button>
</p></td>
</tr>
<?php
$total = + $_SESSION ["amounts"] [$i];
}
$_SESSION ["total"] = $total;
?>
<tr>
<td colspan="2">Total: $<?php echo($total); ?></td>
<td><input type='submit' value='Checkout' /></td>
</tr>
<tr>
<td><button type='submit' name='clear'>Clear cart</button></td>
</tr>
</table>
</form>
<?php } ?>
There's a few things that need fixing in your script, so I'll break them down into their individual parts.
There's a lot of security error checks that should also be done with the code, but as a pure learning exercise, I'm bypassing those factors.
Defining the cart
You're defining the shopping cart as an array:
if (! isset ( $_SESSION ['cart'] )) {
$_SESSION ['cart'] = array ();
}
However, when you add an item to the cart, you're replacing the cart:
// Add
if (isset ( $_POST ["buy"] )) {
$_SESSION ['cart'] = $_POST; //
}
To add an item to the cart, you should be using $cart[] = $_POST
, but, there are additional things to take into account.
Adding to cart
The $cart[] = $_POST
adds the full $_POST
data to the cart, when you only need the product ID. The correct way would be:
// Add
if (isset ( $_POST ["buy"] )) {
// Check the item is not already in the cart
if (!in_array($_POST ["buy"], $_SESSION['cart'])) {
// Add new item to cart
$_SESSION ['cart'][] = $_POST["buy"];
}
}
This would result in the cart storing multiple values. For example, a print_r($_SESSION['cart'])
might show:
array (
0 => 'A123',
1 => 'B456'
);
Each item in this array would be an item that has been added to your cart.
Removing an item from your cart
Now that the structure of $_SESSION['cart']
has been changed, the "remove from cart" action requires updates too. Using a little snippet of code, we can check if the value exists in the array, find its key, and remove it.
// Delete Item
else if (isset ( $_POST ['delete'] )) { // a remove button has been clicked
// Remove the item from the cart
if (false !== $key = array_search($_POST['delete'], $_SESSION['cart'])) {
unset($_SESSION['cart'][$key]);
}
}
Check if the item is in your cart
Further changes to your code would be required to support the new array structure. You can use in_array
to check if your product is contained in the cart array.
<?php
foreach ( $items as $ino => $item ) {
// ... snipped for brevity
// Check if an item is in the cart by checking for the existence of its ID:
if (in_array($ino, $_SESSION['cart'])) { // The $ino would be 'a123' for your first product
echo "<p><button type='submit' name='delete' value='$ino'>Remove</button></p>";
} else {
echo "<button type='submit' name='buy' value='$ino'>Buy</button> ";
}
}
?>
Simplifying your code
In the above code, I've removed some of the code. You are doing the following:
$title = $item ['name'];
$desc = $item ['desc'];
$price = $item ['price'];
echo " <p>$title</p>";
echo " <p>$desc</p>";
echo "<p>\$$price</p>";
This can be simplified to:
echo "<p>$item['name']</p>";
echo "<p>$item['desc']</p>";
echo "<p>\$$item['price']</p>";
Rather than the double $$
in the last line, I personally would use:
echo '<p>$' . number_format($item['name']) . '</p>';
This allows you to format the display of the number easier. Alternatively, you could use money_format
.
Displaying the shopping cart
There are a few problems with this code.
- You're attempting to
echo($_SESSION['cart'])
which won't work. You cannotecho
an array - You're using
foreach ($_SESSION ["cart"] as $i)
incorrectly when attempting to display the values using<?php echo($_SESSION["price"][$i] ); ?>
- You're complicating the code used for the
$total
value - The HTML isn't valid due to a random
</p>
thrown into the mix
The correct way to display this would be:
<?php
// Set a default total
$total = 0;
foreach ( $_SESSION['cart'] as $ino ) {
?>
<tr>
<td>
Name: <?php echo $items[$ino]['name']; ?>
</td>
<td>
Price: <?php echo $items[$ino]["price"]; ?>
</td>
<td>
<button type='submit' name='delete' value='<?php echo $ino; ?>'>Remove</button>
</td>
</tr>
<?php
$total += $items[$ino]['price'];
} // end foreach
?>
Total: $<?php echo $total; ?>
这篇关于使用PHP $ _Session和NO SQL创建一页购物车的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!