将用户输入从<select>转换为变量</select>

时间:2013-03-12 16:13:32

标签: php arrays action

我目前正在开展一个小型大学项目。开发一个基本的电子商务php网站。我们在研讨会上获得了代码或提供的代码,然后我们将根据我们的需求进行定制/开发。

我正在尝试调整以下代码以添加其他信息。 cart.php代码构建购物车功能,显示产品名称,数量,然后允许用户增加/减少数量。

我正在尝试将用户(选定的)产品尺寸添加到购物车。他们可以在product.php上选择。我已经在product.php中为此创建了数据库支持我只需要用户选择的选项然后出现在cart.php中。

我不完全确定如何正确地做到这一点。我的第一个问题是如何将product.php中的用户选择记录到一个变量中,该变量可以转移到cart.php。

第二个问题是如何修改cart.php来执行此操作,您将在cart.php中看到我试图将产品大小添加到表中。

我真的很感激这方面的一些指导。

Product.php

<div align="center"><?php
    session_start();
    //Connect to Session
    include "conn.php";

    //Retrieve Header
    include "header.php";

    //Query

    //Get Product ID
    if (isset($_GET['id'])){
        $product_id = $_GET['id'];

    //Select Product Attributes Query where Product ID is the selected product ID
        $q="SELECT ProductName,img,ProductID,Description,p_spec1,p_spec2,p_spec3,p_spec4,p_spec5,Price,size_1,size_2,size_3,size_4,size_5 FROM Products 
            WHERE ProductID=$product_id";

    //Retrieve and excute query from database and save results into a variable  
        $result = mysqli_query($_SESSION['conn'],$q);

    //Display Product
        if ($row = mysqli_fetch_array($result)){ //Create Product Attribute Array   
            echo "<div>
            <p><b>Name:</b>" .$row[0]."</p>

            <p><img src=".$row[1]."></p>

            <p><b>Product Code:</b>" .$row[2]."</p>

            <p><b><u>Product Description:</b></u></p>
            <p>".$row[3]."</p>

            <p><b><u>Product Spec:</b></u>";

            //Count total product specifications and adjust bullet points 
             for($i=4;$i<9;$i++) {
             if($row[$i]!='')
             echo "<li>".$row[$i]."</li>";
             }
             echo"  
            <p><b>Price: </b>&#163;".$row[9]."</p>

            <p><b>Size:</b><select>";

            //Count total product sizes available and adjust drop-down menu
             for($i=10;$i<15;$i++) {
             if($row[$i]!='')
             echo "<option>".$row[$i]."</option>";
             }
             echo"</select>             
            </p>

            </p>
            </div>";
        }

    //Add Item to basket
        echo "<div><a href=\"cart.php?action=add&product=$product_id,$product_size\"><input type='submit' value='Add to Basket'</a></div>";
    }

    //Retrieve Footer
    include "footer.php";
?>
</div>

我在product.php中假设需要将变量$ product_size操作到cart.php,但是如何将用户选择收集到变量中呢?

Cart.php

<?php

//Start Session
session_start();
include "conn.php"; //Connect to database
include "header.php"; //Retrieve Header

//View the current shopping cart session
function viewcart(){
    if (isset($_SESSION['cart'])){ //if shopping cart is not empty
        $cart = $_SESSION['cart']; //store the cart array into a variable then display the content
        echo "<table border=\"1\"> <tr> <th>Product</th> <th>Size</th> <th>Quantity</th> <th>Action</th></tr>";
        foreach ($cart as $product=>$quantity){
            $q = "SELECT ProductID FROM Products WHERE ProductName = '$product' LIMIT 1";
            $result = mysqli_query($_SESSION['conn'],$q);
            $row = mysqli_fetch_array($result);
            $product_id = $row['ProductID'];
            echo "<tr><td>$product</td>
                <td>$product_size</td>
                <td>$quantity</td><td> 
                <a href=\"?action=delete&product=$product_id\">-</a> 
                <a href=\"?action=add&product=$product_id\">+</a> </td> </tr>";
            mysqli_free_result($result);
        }
        echo "</table>";
        subtotal($cart); //display the subtotal
    } else { //if shopping cart is empty
        echo "<p>Your Basket is empty.</p>";
    }

}
function subtotal($cart){ 
    $total = 0; //initialise total
    if (!empty($cart)){
        foreach ($cart as $product => $quantity){
            $q = "SELECT Price FROM Products WHERE ProductName ='$product' LIMIT 1";
            $result = mysqli_query($_SESSION['conn'],$q);
            $row = mysqli_fetch_array($result);
            $price = $row['Price'];
            $total += $price * $quantity;
        }
        echo "<p>Total: &#163;$total | 
            <a href=\"?action=empty\">Empty cart</a></p>";
    } else {
        unset($_SESSION['cart']); //destroy empty cart
        echo "<p>Your Basket is empty.</p>";
    }
}
function addproduct($product_id, $product_qty){

    $q = "SELECT ProductName FROM Products WHERE ProductID = $product_id LIMIT 1";
    $result = mysqli_query($_SESSION['conn'],$q);
    $row = mysqli_fetch_array($result);
    $product_name = $row['ProductName'];    //get the product name from product id because it is better to display name than id in the cart
    if (isset($_SESSION['cart'])){  //if shopping cart is not empty
        $cart = $_SESSION['cart'];
        if (array_key_exists($product_name, $cart)){ //if the product exists, update quantity
            $cart[$product_name] += $product_qty;
        }
        else {  //otherwise, add new product-quantity pair to the array
            $cart[$product_name]=$product_qty;
        }
    $_SESSION['cart'] = $cart; //write the updated array back to session variable
    }
    else { //if shopping cart is empty
        $cart = array($product_name=>$product_qty); //add product and quantity to the shopping cart
        $_SESSION['cart'] = $cart; //write the updated array back
    }
    mysqli_free_result($result);
}
function deleteproduct($product_id, $product_qty){
    $q = "SELECT ProductName FROM Products WHERE ProductID = $product_id LIMIT 1";
    $result = mysqli_query($_SESSION['conn'],$q);
    $row = mysqli_fetch_array($result);
    $product_name = $row['ProductName'];
    if (isset($_SESSION['cart'])){ //if shopping cart is not empty
        $cart = $_SESSION['cart'];
        if (array_key_exists($product_name, $cart)){ //if product exists,                           update quantity
            $cart[$product_name] -= $product_qty;
            if ($cart[$product_name] == 0){ //if the qty 0, delete key
                unset($cart[$product_name]);
            }
        }
        else { //exception
            echo "<p>Error!</p>";
        }
        $_SESSION['cart'] = $cart; //write array back to session variable
    } else {
        echo "<p>Error!</p>";
    }
    mysqli_free_result($result);
}
function emptycart(){

    if (isset($_SESSION['cart'])){ //if shopping cart                       is not empty
        unset($_SESSION['cart']);
    }
    else {
        echo "<p>Error!</p>";
    }
}


if (isset($_GET['action'])){
    if ($_GET['action']=='view'){
        viewcart();
    } elseif ($_GET['action']=='add'){
        if (isset($_GET['product'])){
            $product_id = $_GET['product'];
            $product_qty = 1; //default product value
            addproduct($product_id, $product_qty);
            viewcart();
        } else {
            echo "<p>There is an error?</p>";
        }
    }
elseif ($_GET['action'] == 'delete'){
        if (isset($_GET['product'])){
            $product_id = $_GET['product'];
            $product_qty = 1; //default product value
            deleteproduct($product_id, $product_qty);
            viewcart();
        }
        else {
            echo "<p>There is an error!</p>";
        }
    } elseif ($_GET['action']=='empty') {
        emptycart();
        viewcart();
    }
    else {
        echo "<p>There is an error! </p>";
    }
}
else {   echo "<p>There is an error!</p>"; }

include "footer.php"; //template design part
?>

P.S我知道SQL注入问题。

谢谢!

2 个答案:

答案 0 :(得分:1)

我前段时间构建了类似于此的东西,并面临同样(相当常见)的问题。

该解决方案要求您创建一个会话变量来存储所选的产品ID。我想我在会话中存储了一个或多个数组,并使用这些信息来填充结帐页面。

我还将会话数据存储在一个表中,以便用户可以在会话之间访问它, 但这是一个更高级的功能。

Take Away:使用会话变量来存储产品ID的数组

答案 1 :(得分:0)

这里有一些根本性的缺陷。

首先,创建有效的HTML。确保表单包含在<form></form>标记中。该表单应该有一个操作:<form action="cart.php" method="POST">

您选择的“尺寸”需要有一个名称:<select name="productSize">