Cart System for shop website puts only 1 item [closed]

I am making an online market website thing. I have this problem here, It is only adding one product and that’s it. So if I add multiple products, it will only add one product to the cart and will +1 to quantity whenever you add other products. Even if I add one then refresh the page and add others, it will increase the quantity of the first added product.

Now let me show you my code:

<?php

include 'db.php';

$product_query = "SELECT * FROM products ORDER BY product_id DESC LIMIT 4";
$run_query = mysqli_query($con, $product_query);

//finding user stuff
$user_id = '0';
if (isset($_SESSION["uid"])) {
    $sqlu = "SELECT first_name FROM user_info WHERE user_id='$_SESSION[uid]'";
    // Insert data into persons table
    $user_id = $row["user_id"];
} else {
    $user_id = '0';
}

if (mysqli_num_rows($run_query) > 0) {
    while ($row = mysqli_fetch_array($run_query)) {
        $pro_id = $row['product_id'];
        $pro_title = $row['product_title'];
        $pro_price = $row['product_price'];
        $pro_image = $row['product_image'];
        $pro_old_price = $row['product_old_price'];

        echo "
                
                        
                                
                                <div class="product">
                                    <a href="https://stackoverflow.com/questions/77047891/product.php?p=$pro_id"><div class="product-img">
                                        <img src="product_images/$pro_image" style="max-height: 170px;width:100%;" alt="">
                                        <div class="product-label" style="top:-13px;left:3px;">
                                            <span class="new">NEW</span>
                                        </div>
                                        <div class="product-btns">
                                            <button pid='$pro_id' id='wishlist' class="add-to-wishlist" style=""><i class="fa fa-heart-o"></i></button>
                                        </div>
                                    </div></a>
                                    <div class="product-body" style="background-color:#1c1c1c;">
                                        
                                        <h6 class="product-price header-cart-item-info" style="color:#D10024;">$pro_price TMT 
                                        ";
        if ($pro_old_price > 0) {
            echo "<del class="product-price product-old-price" style="margin-bottom: 10px; color: gray; font-size: 14px;">$pro_old_price TMT </del></h6>";
        } else {
            echo "<del class="product-price product-old-price" style="margin-bottom: 10px; color: gray; font-size: 14px;"></del></h6>";
        }
        echo "<h6 class="product-name header-cart-item-name"><a href="https://stackoverflow.com/questions/77047891/product.php?p=$pro_id">$pro_title</a></h6>";
        /*$rating_query = "SELECT ROUND(AVG(rating),1) AS avg_rating  FROM reviews WHERE product_id='$pro_id '";
                            $run_review_query = mysqli_query($con,$rating_query);
                            $review_row = mysqli_fetch_array($run_review_query);

                            if($review_row > 0){
                                $avg_count=$review_row["avg_rating"];
                                    $i=1;
                                    while($i <= round($avg_count)){
                                        $i++;
                                        echo'
                                        <i class="fa fa-star"></i>';
                                    }
                                    $i=1;
                                    while($i <= 5-round($avg_count)){
                                        $i++;
                                        echo'
                                        <i class="fa fa-star-o empty"></i>';
                                    }

                            }*/
        echo "
                                            "; //<button class="quick-view" ><i class="fa fa-eye"></i><span class="tooltipp">Быстрый просмотр</span></button>
        $value = -1;
        if (isset($_SESSION["uid"])) {
            $user_id = $_SESSION["uid"];

            // Use a single equal sign (=) to assign the value of the SQL query to the variable $value
            $value = "SELECT qty FROM cart WHERE p_id = '$pro_id' AND user_id = '$user_id'";

            // Use the mysqli_query function to execute the SQL query and get the result
            $result = mysqli_query($con, $value);

            // Check for errors
            if (!$result) {
                echo "Error executing query: " . mysqli_error($conn);
            } else {
                // Use the mysqli_fetch_assoc function to get the associative array of the result
                $row = mysqli_fetch_assoc($result);
                // Use $row["qty"] to access the quantity value
                if ($row > 0) {
                    $value = $row["qty"];
                } else {
                    $value = 0;
                }
            }
        } else {
            $user_id = -1;

            // Use a single equal sign (=) to assign the value of the SQL query to the variable $value
            $value = "SELECT qty FROM cart WHERE p_id = '$pro_id' AND user_id = '$user_id'";

            // Use the mysqli_query function to execute the SQL query and get the result
            $result = mysqli_query($con, $value);

            // Check for errors
            if (!$result) {
                echo "Error executing query: " . mysqli_error($conn);
            } else {
                // Use the mysqli_fetch_assoc function to get the associative array of the result
                $row = mysqli_fetch_assoc($result);
                // Use $row["qty"] to access the quantity value
                if ($row > 0) {
                    $value = $row["qty"];
                } else {
                    $value = 0;
                }
            }
        }
        if ($value < 0) {
            $value = 0;
        }

        echo "
                                    <div class="add-to-cart">
                                    <form id='myForm' action='action.php' method='POST'>
                                        <button type="button" pid='$pro_id' id='productt$pro_id' class="rem-from-cart-btn block12-btn-towishlist" href="#" onclick='decreaseAmount$pro_id()' name="fromCart$pro_id">-</button>
                                        <input type="number" min='0' class="qty" id='qty-cart$pro_id' value="$value"readonly></input>
                                        <button type="button" pid='$pro_id' id='product$pro_id' class="add-to-cart-btn block2-btn-towishlist" href="#" onclick='increaseAmount$pro_id()'name="toCart$pro_id">+</button>
                                        
                                        <script type="text/javascript">
                                        
                                        // Get the form element by its id
                                        var form = document.getElementById('myForm');

                                        // Get all the buttons with the class 'rem-from-cart-btn'
                                        var button = document.getElementById('productt$pro_id');

                                        button.addEventListener('click', function(event) {
                                        // Prevent the default button behavior
                                        //event.preventDefault();

                                        // Create a new XMLHttpRequest object
                                        var xhr = new XMLHttpRequest();

                                        // Specify the PHP script that will handle the request
                                        var url="body.php";

                                        // Use event.target.getAttribute('pid') to get the pid of the button
                                        var data="pidm=" + event.target.getAttribute('pid');

                                        // Open a POST request
                                        xhr.open('POST', url, true);

                                        // Set the request header for sending form data
                                        xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');

                                        // Send the request with the data
                                        xhr.send(data);

                                        // Define a callback function that runs when the request is successful
                                        xhr.onload = function() {
                                        };
                                        });
                                        
                                        
                                        // Get all the buttons with the class 'rem-from-cart-btn'
                                        var button = document.getElementById('product$pro_id');

                                        button.addEventListener('click', function(event) {
                                        // Prevent the default button behavior
                                        //event.preventDefault();

                                        // Create a new XMLHttpRequest object
                                        var xhr = new XMLHttpRequest();

                                        // Specify the PHP script that will handle the request
                                        var url="body.php";

                                        // Use event.target.getAttribute('pid') to get the pid of the button
                                        var data="pidp=" + event.target.getAttribute('pid');
                                        
                                        // Open a POST request
                                        xhr.open('POST', url, true);

                                        // Set the request header for sending form data
                                        xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');

                                        // Send the request with the data
                                        xhr.send(data);

                                        // Define a callback function that runs when the request is successful
                                        xhr.onload = function() {
                                        };
                                        });
                                        
                                        
                                        
                                        function increaseAmount$pro_id() {
                                        const qty = document.getElementById('qty-cart$pro_id');

                                        // Get the current value of the input field.
                                        currentValue = qty.getAttribute('value');

                                        // Check if the current value is 0.
                                        if (currentValue === 0) {
                                            // Set the new value to 1.
                                            qty.setAttribute('value',1);
                                        } else {
                                            // Increase the value by 1.
                                            currentValue++;

                                            // Set the value of the input field to the new value.
                                            qty.setAttribute('value',currentValue);
                                        }
                                        
                                        }
                                        
                                        function decreaseAmount$pro_id() {
                                        const qty = document.getElementById('qty-cart$pro_id');

                                        // Get the current value of the input field.
                                        currentValue = qty.getAttribute('value');

                                        // Check if the current value -1 is lower 0.
                                        if (currentValue - 1 < 0) {
                                            // Set the new value to 0.
                                            qty.setAttribute('value',0);
                                        } else {
                                            // Decrease the value by 1.
                                            currentValue--;

                                            // Set the value of the input field to the new value.
                                            qty.setAttribute('value',currentValue);
                                        }
                                        }
                                        
                                        
                                        
                                        
                                        </script>
                                        </form>
                                    </div>
                                    </div>
                                </div>
                            
                            
                        
            ";

        if (isset($_POST["pidm"])) { //the hell is this SHIIIIIT
            $p_id = $_POST["pidm"];

            $ip_add = getenv("REMOTE_ADDR");

            if (isset($_SESSION["uid"])) {
                $user_id = $_SESSION["uid"];

                $sql = "INSERT INTO `cart`
            (`p_id`, `ip_add`, `user_id`) 
            VALUES ('$p_id','$ip_add','$user_id')
            ON DUPLICATE KEY UPDATE qty = qty - 1";
                if (mysqli_query($con, $sql)) {
                    $sql = "DELETE FROM wishlist WHERE p_id = '$p_id' AND user_id = '$_SESSION[uid]'";

                    if (mysqli_query($con, $sql)) {
                        echo "<div class="alert alert-danger">
                                    <a href="#" class="close" data-dismiss="alert" aria-label="close">&times;</a>
                                    <b>Product is removed from wishlist and added to cart</b>
                            </div>";
                        $sql = "DELETE FROM cart
                            WHERE p_id = '$p_id' AND ip_add = '$ip_add' AND user_id = '$user_id' AND qty < 1";
                        if (mysqli_query($con, $sql)) {
                        }
                    }
                }
            } else {
                $sql = "INSERT INTO `cart`
            (`p_id`, `ip_add`, `user_id`) 
            VALUES ('$p_id','$ip_add','-1')
            ON DUPLICATE KEY UPDATE qty = qty - 1";
                if (mysqli_query($con, $sql)) {
                    $sql = "DELETE FROM wishlist WHERE p_id = '$p_id' AND ip_add = '$ip_add'";

                    if (mysqli_query($con, $sql)) {
                        echo "<div class="alert alert-danger">
                                    <a href="#" class="close" data-dismiss="alert" aria-label="close">&times;</a>
                                    <b>Product is removed from wishlist and added to cart</b>
                            </div>";

                        $sql = "DELETE FROM cart
                            WHERE p_id = '$p_id' AND ip_add = '$ip_add' AND user_id = -1 AND qty < 1";
                        mysqli_query($con, $sql);
                        exit();
                    }
                }
            }
        }

        if (isset($_POST["pidp"])) {
            $p_id = $_POST["pidp"];

            $ip_add = getenv("REMOTE_ADDR");

            if (isset($_SESSION["uid"])) {
                $user_id = $_SESSION["uid"];

                $sql = "INSERT INTO `cart`
            (`p_id`, `ip_add`, `user_id`) 
            VALUES ('$p_id','$ip_add','$user_id')
            ON DUPLICATE KEY UPDATE qty = qty + 1";
                if (mysqli_query($con, $sql)) {
                    $sql = "DELETE FROM wishlist WHERE p_id = '$p_id' AND user_id = '$_SESSION[uid]'";

                    if (mysqli_query($con, $sql)) {
                        echo "<div class="alert alert-danger">
                                    <a href="#" class="close" data-dismiss="alert" aria-label="close">&times;</a>
                                    <b>Product is removed from wishlist and added to cart</b>
                            </div>";
                    }
                }
            } else {
                $sql = "INSERT INTO `cart`
            (`p_id`, `ip_add`, `user_id`) 
            VALUES ('$p_id','$ip_add','-1')
            ON DUPLICATE KEY UPDATE qty = qty + 1";
                if (mysqli_query($con, $sql)) {
                    $sql = "DELETE FROM wishlist WHERE p_id = '$p_id' AND ip_add = '$ip_add'";

                    if (mysqli_query($con, $sql)) {
                        echo "<div class="alert alert-danger">
                                    <a href="#" class="close" data-dismiss="alert" aria-label="close">&times;</a>
                                    <b>Product is removed from wishlist and added to cart</b>
                            </div>";
                        exit();
                    }
                }
            }
        }
    }
}

So, as you can see I loop with while and get all the products. As you can see every button has a JavaScript thing.

  • 3

    Warning: You are wide open to SQL Injections and should use parameterized prepared statements instead of manually building your queries. They are provided by PDO or by MySQLi. Never trust any kind of input! Even when your queries are executed only by trusted users, you are still in risk of corrupting your data. Escaping is not enough!

    – 

  • Oh. I got it Mr. Dharman! Thank you for telling me! I am new in this. Will definitely look into it. I’m just learning and was making something for myself for project. Learning a lot along the way! Thank you for telling me this. I will try it tomorrow

    – 

Leave a Comment