首页 > 解决方案 > 添加到购物车按钮未在数据库中添加项目

问题描述

我是 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>
            ";

        }
    }
}

标签: php

解决方案


我无法真正为您解决这个问题,因为问题可能在任何地方,但是您有一些问题需要解决,希望我所展示的一些内容会有用:

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 库要容易得多。


推荐阅读