如何将产品插入购物车然后注册或登录

时间:2016-06-02 23:15:43

标签: php mysql database

我有产品,订单详情和客户表
当订户登录时,orderdetails表格有products_id (FK) customers_id(FK) Quantitysize,并且在orderdetails表中添加项目,我希望允许客户即使没有登录也可以将商品/产品添加到购物车,然后他们可以登录或注册
我需要另一张桌子吗?

数据库
productTable (products_id(pk), products_name , price,Quantity ,size )
customerTable (customers_id(pk), cust_name, cust_email )
orderdetails (products_id(FK), customers_id(FK), price,Quantity,size )

     <?php
include'config.php'; 
  session_start();  

if(isset($_SESSION['product_name']) && !empty($_SESSION['product_name'])) {
 $products_name =$_SESSION['product_name'];
 }
if(isset($_SESSION['products_price']) && !empty($_SESSION['products_price'])) {
 $products_price =$_SESSION['products_price'];
}


 if(isset($_SESSION['Quantity']) && !empty($_SESSION['Quantity'])) {
  $Quantity = $_SESSION['Quantity'];

 } 
  if(isset($_SESSION['product_id']) && !empty($_SESSION['product_id'])) {
  $product_id =   $_SESSION['product_id'];
 }
   if(isset($_SESSION['customers_id']) && !empty($_SESSION['customers_id'])) {
         $customers_id =   $_SESSION['customers_id'];

   } 
    if(isset($_SESSION['size']) && !empty($_SESSION['size'])) {
       $size =   $_SESSION['size'];

   } 
 $query = "INSERT INTO orderdetails  (products_id,customers_id,price,Quantity ,size) VALUES ('$product_id','$customers_id','$products_price','$Quantity','$size')";
mysqli_query($conn,$query) ;
    mysqli_close($conn);




?>  

1 个答案:

答案 0 :(得分:0)

不一定。如果customers_id不是外键或其中的一部分,则只需为未登录的每个用户生成一个新的customer_id并使用该customer_id。一旦用户登录,您就会更新表格:

UPDATE orderdetails SET customers_id = <id of user logged in>
    WHERE customers_id = <previous temporary id>

如果会话过期,您将再次删除任何条目(当然,未登录的用户的购物车无法在过期的会话中存活):

DELETE FROM orderdetails WHERE customers_id = <temporary id> 

如果customers_id 是外键,则需要在第一项添加到购物车后立即另外创建临时客户条目。然后,当会话到期时,也删除此条目。并且您需要在注册用户登录后立即删除临时条目,并在orderdetails中更新customer_id。