“添加到购物车”按钮未在数据库中添加项目

时间:2018-11-02 23:58:59

标签: php

我是php的新手,正在尝试将项目添加到数据库表(购物车)中,但是当我单击“添加到购物车”时,什么都没有发生。通过下面的功能getPro显示该按钮。

function cart(){
if(isset($_GET['add_cart'])){

    global $con;    

    $ip = getIp();

    $pro_id = $_GET['add_cart'];

    $check_pro = "SELECT * FROM cart where ip_add='$ip' and p_id='$pro_id'";

    $run_check = mysqli_query($con, $check_pro);

    if(mysqli_num_rows($run_check)>0){
        echo "";
    }
    else {

        $insert_pro = "insert into cart(p_id,ip_add) values ('$pro_id','$ip')";

        $run_pro = mysqli_query($con, $insert_pro);

            echo "<script>window.open('index.php','_self')</script>";

    }
}}

“添加到购物车”按钮将被此功能回显。

function getPro(){

    global $con;

    $get_pro = "select * from products order by RAND() LIMIT 0,6";

    $run_pro = mysqli_query($con, $get_pro);

        while ($row_brand_pro=mysqli_fetch_array($run_pro)) {

            $pro_id = $row_brand_pro['product_id'];
            $pro_cat = $row_brand_pro['product_cat'];
            $pro_brand = $row_brand_pro['product_brand'];
            $pro_title = $row_brand_pro['product_title'];
            $pro_price  = $row_brand_pro['product_price'];
            $pro_image = $row_brand_pro['product_image'];

            echo "
               <a href='index.php?add_cart=$pro_id'><button style='float:right;'>Add to Cart</button></a>
                </div>
            ";

        }
    }
}

1 个答案:

答案 0 :(得分:0)

我无法真正为您解决此问题,因为问题可能存在于任何地方,但是您有一些问题应该解决,希望我所展示的一些内容会有所帮助:

1)如果可能的话,请改用框架,自由框架已经(安全地)解决了您正在做的许多事情。如果您对此一无所知:

2)尝试避免使用global,您可以改为注入数据库:

cart($con);

3)进一步拆分您的功能,每个功能做的太多:

# Try to make this more flexible by adding the limits as variables
# Also, you might decide that random is not a great idea, so this allows you
# to change that at each instance
# Also, if you leave the columns flexible, you will make your function that
# much more useful
function getProducts($con, $cols = '*', $page = 0, $limit = 6, $rand = true)
{
    # Perhaps you don't want to limit one day
    $limitSql = (!empty($page) || !empty($limit))? "LIMIT {$page}, {$limit}" : "";
    # This allows you to insert an array and only select certain columns
    $cols  = (is_array($cols))? implode(", ", $cols) : $cols;
    # Only add the randomness if you want to (default is to randomize)
    $sql   = ($rand)? "ORDER BY RAND()" : '';
    # Create your dynamic statement
    $stmnt = "SELECT {$cols} FROM products {$sql} {$limitSql}";
    $query = mysqli_query($con, $stmnt);
    # Have this just assemble the values, don't echo anything
    while ($result = mysqli_fetch_array($query)) {
        $row[] = $result;
    }
    # Send back the results
    return (!empty($row))? $row : [];
}

使用此功能:

# This would give you results with just the two columns with 10 results, no random
$products = getProducts($con, array("product_id", "product_title"), 0, 10, false);
# This should just return the count
$products = getProducts($con, "COUNT(*) as count", false, false, false);

因此,既然您已经有了此功能,则可以在视图中编写循环:

<?php foreach(getProducts($con, 'product_id') as $row): ?>

<!-- Now you have only pulled the one column required for this use -->
<a href="index.php?add_cart=<?php echo $row['product_id'] ?>">Add to Cart</a>

<?php endforeach ?>

4)此购物车功能存在更多问题,存在一些问题。 a)如果来自用户的值不是数字,则需要绑定参数,所拥有的是sql注入并且是安全问题b)您应将此函数拆分为两个,c)您应在视图外放置回显。 d)如果您通过ip存储购物车,我可能不会这样做,如果一台以上的计算机使用VPN或在同一网络上,则可以有多个具有相同ip的计算机。 Cookie可能是更好的解决方案:

function itemExists($con, $pid, $ip)
{
    $stmnt = "SELECT * FROM cart WHERE ip_add = '{$ip}' and p_id = '{$pid}'";
    $query = mysqli_query($con, $stmnt);

    return (mysqli_num_rows($query) > 0);
}

function addToCart($con, $pid, $qty = 1)
{
    # Since you aren't binding, you need some sort of safeguard here, I am assuming
    # your product id values are numeric. If not, you definitely need to bind parameters
    if(!is_numeric($pid))
        return false;
    # Same here, you need to make sure nothing but numbers get through (or bind)
    if(!is_numeric($qty))
        $qty = 1;
    # Pass on your connection and pid, inject the getIp() function if you choose 
    # to keep using it
    $itemExists = itemExists($con, $pid, getIp());
    # Confirm the item has no row in database
    if($itemExists)
        # Stop if it does
        return false;
    # You may want to echo here to see if this is what you expect
    $stmnt = "insert into cart(p_id, ip_add) values ('{$pid}', '{$ip}')";
    # I use PDO, but I am sure you can get an error back on this if the sql
    # fails for whatever reason, that is a good place to start for your issue
    $query = mysqli_query($con, $stmnt);
    # Run this again to make sure it inserted
    return itemExists($con, $pid, getIp());
}

现在在您看来:

if(!empty($_GET['add_cart'])) {
    # When you add to cart, there should be some feed back to whether it was successful
    $success = addToCart($con, $_GET['add_cart']);
    # If not you can echo it
    if(!$success)
        echo '<div class="msg error">An error occurred adding item to cart.</div>';
}

无论如何,希望这很有用,但是您应该考虑1)使用框架,如果没有,则使用mysqli(或PDO)的OOP版本,因为参数绑定比功能更容易(我发现) mysqli库。