0

I'm trying to follow a simple add to cart tutorial using php, sql, with my database on phpmyadmin, but when the user clicks "add to cart", nothing is displayed in the shopping cart table.

Any non-php solutions are welcome. Here is the tutorial: http://www.webslesson.info/2016/08/simple-php-mysql-shopping-cart.html

Thank you!

<?php
session_start();
require_once ('database_conn.php');
if (isset($_POST["add_to_cart"])) {
    if (isset($_SESSION["shopping_cart"])) {
        $item_array_id = array_column($_SESSION["shopping_cart"], "productID");
        if (!in_array($_GET["id"], $item_array_id)) {
            $count = count($_SESSION["shopping_cart"]);
            $item_array = array(
                'productID' => $_GET["productID"],
                'productName' => $_POST["productName"],
                'productPrice' => $_POST["productPrice"],
                'productAisle' => $_POST["productAisle"]
            );
            $_SESSION["shopping_cart"][$count] = $item_array;
        }
    } else {
        $item_array = array(
            'productID' => $_GET["productID"],
            'productName' => $_POST["productName"],
            'productPrice' => $_POST["productPrice"],
            'productAisle' => $_POST["productAisle"]
        );
        $_SESSION["shopping_cart"][0] = $item_array;
    }
}
if (isset($_GET["action"])) {
    if ($_GET["action"] == "delete") {
        foreach ($_SESSION["shopping_cart"] as $keys => $values) {
            if ($values["item_id"] == $_GET["id"]) {
                unset($_SESSION["shopping_cart"][$keys]);
                echo '<script>alert("Item Removed")</script>';
                echo '<script>window.location="add.php"</script>';
            }
        }
    }
}
?>
<!DOCTYPE html>
<html>
    <head>
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
        <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
    </head>
    <body>
        <br />
        <div class="container" style="width:700px;">
            <?php
            $name = isset($_REQUEST['name']) ? $_REQUEST['name'] : null;
            $sqlProducts = "SELECT productID, productName, productPrice, productImage, productAisle

                    FROM s_products WHERE productName LIKE '%$name%'";
            $rProducts = mysqli_query($conn, $sqlProducts) or die(mysqli_error($conn));

            while ($row = mysqli_fetch_assoc($rProducts)) {
                $productID = $row['productID'];
                $productName = $row['productName'];
                $productImage = $row['productImage'];
                $productAisle = $row['productAisle'];
                {
                    ?>
                    <div class="col-md-4">
                        <form method="post" action="add.php?action=add&id=<?php echo $row["id"]; ?>">
                            <div style="border:1px solid #333; background-color:#f1f1f1; border-radius:5px; padding:16px;" align="center">
                                <img src="<?php echo $row["productImage"]; ?>" class="img-responsive" /><br />
                                <h4 class="text-info"><?php echo $row["productName"]; ?></h4>
                                <h4 class="text-danger">$ <?php echo $row["productPrice"]; ?></h4>
                                <input type="text" name="quantity" class="form-control" value="1" />
                                <input type="hidden" name="hidden_name" value="<?php echo $row["productName"]; ?>" />
                                <input type="hidden" name="hidden_price" value="<?php echo $row["productPrice"]; ?>" />
                                <input type="submit" name="add_to_cart" style="margin-top:5px;" class="btn btn-success" value="Add to Cart" />
                            </div>
                        </form>
                    </div>
                    <?php
                }
            }
            ?>
            <div style="clear:both"></div>
            <br />
            <h3>Order Details</h3>
            <div class="table-responsive">
                <table class="table table-bordered">
                    <tr>
                        <th width="40%">Item Name</th>
                        <th width="10%">Quantity</th>
                        <th width="20%">Price</th>
                        <th width="15%">Total</th>
                        <th width="5%">Action</th>
                    </tr>
                    <?php
                    if (!empty($_SESSION["shopping_cart"])) {
                        $total = 0;
                        foreach ($_SESSION["shopping_cart"] as $keys => $values) {
                            ?>
                            <tr>
                                <td><?php echo "$productName"; ?></td>
                                <td><?php echo "$productPrice"; ?></td>
                                <td>$ <?php echo "$productAisle"; ?></td>

                                <td><a href="add.php?action=delete&id=<?php echo "$productID";
                        }
                        ?>"><span class="text-danger">Remove</span></a></td>
                        </tr>

                        <tr>
                            <td colspan="3" align="right">Total</td>
                            <td align="right">$ <?php echo number_format($total, 2); ?></td>
                            <td></td>
                        </tr>
                        <?php
                    }
                    ?>
                </table>
            </div>
        </div>
        <br />
    </body>
</html>
Rotimi
  • 4,494
  • 4
  • 16
  • 27
aero
  • 3
  • 3
  • When you click add to cart, what kind of data is send to the server? Try posting what the request body looks like so we can help – Syntactic Fructose Apr 03 '18 at 20:03
  • Are you checking for [errors](https://stackoverflow.com/questions/1053424/how-do-i-get-php-errors-to-display)? – ficuscr Apr 03 '18 at 20:03
  • Instead of checking for `$_POST['add_to_cart']`, why not check for `$_REQUEST['action'] == "add"`.... – Adam J Apr 03 '18 at 20:42
  • I am checking for errors, and i just tried that @webdevsoup but no luck yet. thank you – aero Apr 03 '18 at 21:00

1 Answers1

0

Giving you a whole reworked code base for you.

<?php
session_start();
require_once('database_conn.php');
if (isset($_POST["add_to_cart"])) {
    if (isset($_SESSION["shopping_cart"]) && !empty($_SESSION['shopping_cart'])) {
        $item_array_id = array_column($_SESSION["shopping_cart"], "productID");
        if (!in_array($_GET["id"], $item_array_id)) {
            $count = count($_SESSION["shopping_cart"]);
            $item_array = array(
                'productID' => $_GET["productID"],
                'productName' => $_POST["productName"],
                'productPrice' => $_POST["productPrice"],
                'productAisle' => $_POST["productAisle"]
            );
            $_SESSION["shopping_cart"][$count] = $item_array;
        }
    } else {
        $item_array = array(
            'productID' => $_GET["productID"],
            'productName' => $_POST["productName"],
            'productPrice' => $_POST["productPrice"],
            'productAisle' => $_POST["productAisle"]
        );
        $_SESSION["shopping_cart"][0] = $item_array;
    }
}
if (!empty($_GET["action"])) {
    switch ($_GET['action']) {
        case 'delete':
            foreach ($_SESSION["shopping_cart"] as $keys => $values) {
                if ($values["item_id"] == $_GET["id"]) {
                    unset($_SESSION["shopping_cart"][$keys]);
                    echo '<script>alert("Item Removed")</script>';
                    echo '<script>window.location="add.php"</script>';
                }
            }
            break;
        case 'add':
            if (isset($_SESSION["shopping_cart"]) && !empty($_SESSION['shopping_cart'])) {
                $item_array_id = array_column($_SESSION["shopping_cart"], "productID");
                if (!in_array($_GET["id"], $item_array_id)) {
                    $count = count($_SESSION["shopping_cart"]);
                    $item_array = array(
                        'productID' => $_GET["productID"],
                        'productName' => $_POST["productName"],
                        'productPrice' => $_POST["productPrice"],
                        'productAisle' => $_POST["productAisle"]
                    );
                    $_SESSION["shopping_cart"][$count] = $item_array;
                }
            } else {
                $item_array = array(
                    'productID' => $_GET["productID"],
                    'productName' => $_POST["productName"],
                    'productPrice' => $_POST["productPrice"],
                    'productAisle' => $_POST["productAisle"]
                );
                $_SESSION["shopping_cart"][0] = $item_array;
            }
            break;
    }
}
?>
<!DOCTYPE html>
<html>
<head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css"/>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
</head>
<body>
<br/>
<div class="container" style="width:700px;">
    <?php
    $name = isset($_REQUEST['name']) ? $_REQUEST['name'] : null;
    $sqlProducts = "SELECT productID, productName, productPrice, productImage, productAisle

                    FROM s_products WHERE productName LIKE '%$name%'";
    $rProducts = mysqli_query($conn, $sqlProducts) or die(mysqli_error($conn));

    while ($row = mysqli_fetch_assoc($rProducts)) {
        ?>
        <div class="col-md-4">
            <form method="post" action="add.php?action=add&productID=<?php echo $row["id"]; ?>">
                <div style="border:1px solid #333; background-color:#f1f1f1; border-radius:5px; padding:16px;"
                     align="center">
                    <img src="<?php echo $row["productImage"]; ?>" class="img-responsive"/><br/>
                    <h4 class="text-info"><?php echo $row["productName"]; ?></h4>
                    <h4 class="text-danger">$ <?php echo $row["productPrice"]; ?></h4>
                    <input type="text" name="quantity" class="form-control" value="1"/>
                    <input type="hidden" name="productName" id="productName" value="<?= $row["productName"] ?>"/>
                    <input type="hidden" name="productPrice" id="productPrice" value="<?= $row["productPrice"] ?>"/>
                    <input type="hidden" name="productAisle" id="productAisle" value="<?= $row['productAisle'] ?>"/>
                    <input type="hidden" name="hidden_name" value="<?php echo $row["productName"]; ?>"/>
                    <input type="hidden" name="hidden_price" value="<?php echo $row["productPrice"]; ?>"/>
                    <input type="submit" name="add_to_cart" style="margin-top:5px;" class="btn btn-success"
                           value="Add to Cart"/>
                </div>
            </form>
        </div>
        <?php
    }
    ?>
    <div style="clear:both"></div>
    <br/>
    <h3>Order Details</h3>
    <div class="table-responsive">
        <table class="table table-bordered">
            <tr>
                <th width="40%">Item Name</th>
                <th width="10%">Quantity</th>
                <th width="20%">Price</th>
                <th width="15%">Total</th>
                <th width="5%">Action</th>
            </tr>
            <?php
            if (!empty($_SESSION["shopping_cart"])) {
                $total = 0;
                foreach ($_SESSION["shopping_cart"] as $keys => $values) {
                    ?>
                    <tr>
                        <td><?= $values['productName'] ?></td>
                        <td><?= $values['productPrice'] ?></td>
                        <td>$ <?= $values['productAisle'] ?></td>
                        <td><a href="add.php?action=delete&id=<?= $values['productID'] ?>"><span class="text-danger">Remove</span></a>
                        </td>
                    </tr>
                    <?php
                }
                ?>

                <tr>
                    <td colspan="3" align="right">Total</td>
                    <td align="right">$ <?php echo number_format($total, 2); ?></td>
                    <td></td>
                </tr>
                <?php
            }
            ?>
        </table>
    </div>
</div>
<br/>
</body>
</html>
Adam J
  • 463
  • 2
  • 14
  • When you say it doesn't work, are you getting any errors? Is it giving you any errors? – Adam J Apr 03 '18 at 21:02
  • no kind of errors are coming up, there is just nothing happening at all. – aero Apr 03 '18 at 21:02
  • There's nothing happening because all you're doing with the code you posted is saving it to $_SESSION. There's nothing else going on. At the end of the code, before your closing PHP tag, type in `print_r($_SESSION['shopping_cart']);`, and you'll see it. – Adam J Apr 03 '18 at 21:05
  • It is now giving an unidentified index error for shopping_cart. tried to fix that by wrapping it in a statement but it went back to nothing happening. Maybe i'm doing something wrong, i'm not advanced at all in php so apologies for this. – aero Apr 03 '18 at 21:16
  • No worries. Are you using my solution above, or the original code you submitted? – Adam J Apr 03 '18 at 21:33
  • using your solution – aero Apr 03 '18 at 21:37
  • That's odd... I plug your solution in, and it works fine. Try adding errors to the top of your page. `ini_set('display_errors', 1); ini_set('display_startup_errors', 1); error_reporting(E_ALL);` – Adam J Apr 03 '18 at 21:44
  • the only error showing is still the unidentified index for shopping_cart due to print_r($_SESSION['shopping_cart']); – aero Apr 03 '18 at 21:52
  • I'm not sure what to tell you, as I take what you posted above, put it on my local machine, and it puts it in the table just fine. I'd suggest restarting your browser, since you're storing to session. However, if you're still having issues, I could find a way to do it via jQuery for you, but it would take a bit, and not sure it's what you're needing. – Adam J Apr 03 '18 at 21:54
  • just restarted it and its working so thank you! however still getting unidentified index errors for the productName etc on lines 27 then again on 57 (may be different lines for you) is this a quick fix? – aero Apr 03 '18 at 22:05
  • I'd have to look at it later, headed home right now. – Adam J Apr 03 '18 at 22:08
  • Also having an issue where under order details it echos "Array ( [0] => Array ( [productID] => [productName] => [productPrice] => [productAisle] => ) [1] => Array ( [productID] => [productName] => [productPrice] => [productAisle] => ) )" and after adding to cart an error for undefined variable productPrice on line 142 in the table – aero Apr 03 '18 at 22:51
  • Ok, if it echos the Array, that's your session variable. Remove the `print_r($_SESSION)` and remove the errors being on. Then Refresh, and see if you still have all of that. – Adam J Apr 04 '18 at 13:19
  • that worked thank you, only problems left are undefined index and variable – aero Apr 04 '18 at 13:34
  • @dulcie - Take a look at my answer now. I completely redid the code base for you. – Adam J Apr 04 '18 at 14:57
  • thank you for taking the time do this for me. the new code works great for adding and deleting, however still getting undefined index error after adding to cart for lines 19-22 then 44-47 – aero Apr 04 '18 at 15:25
  • @dulcie - Last edit there for you. You should be all set now. – Adam J Apr 04 '18 at 15:30
  • works perfectly! thank you so much for your patience and taking the time to help me with this – aero Apr 04 '18 at 15:33
  • @dulcie - No problem. Make sure you accept the answer, and upvote. Thanks. – Adam J Apr 04 '18 at 15:34