Click here to Skip to main content
15,887,886 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
I want to create a shopping cart but right now I have this problem that whenever someone presses the add to cart button it will add item from the while loop into the chart and not just one item how will I fix this??

index.php
PHP
<pre><!-- session_start();  geeft error a sessin has already started -->
<?php 
$_SESSION['basket'] = array();
error_reporting(E_ALL);
ini_set('display_errrors', '1');
?>
<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="utf-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no" />
        <meta name="description" content="" />
        <meta name="author" content="" />
        <title>Shop Homepage - Start Bootstrap Template</title>
        <!-- Favicon-->
        <link rel="icon" type="image/x-icon" href="assets/favicon.ico" />
        <!-- Bootstrap icons-->
        <link href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.5.0/font/bootstrap-icons.css" rel="stylesheet" />
        <!-- Core theme CSS (includes Bootstrap)-->
        <link href="css/styles.css" rel="stylesheet" />
        <link href="css/stylecart.css" rel="stylesheet" />
        <script src="js/scripts.js" async></script>

    </head>
    <style>
        body {
        font-family: Arial, Helvetica, sans-serif;
        font-size: 20px;
        }

        #myBtn {
        display: none;
        position: fixed;
        bottom: 20px;
        right: 30px;
        z-index: 99;
        font-size: 18px;
        border: none;
        outline: none;
        background-color: black;
        color: white;
        cursor: pointer;
        padding: 25px;
        border-radius: 50px;
        }

        #myBtn:hover {
        background-color: #555;
        }
    </style>
    <body>
        
        <!-- Navigation-->
        <?php include "navbar.php"?>
        <?php if(isset($_SESSION['USER_ID'])){ ?>
        <!-- Header-->
        <header class="bg-dark py-5">
            <div class="container px-4 px-lg-5 my-5">
                <div class="text-center text-white"> <!--Het werkt -->
                    <h1 class="display-4 fw-bolder">Goedemorgen, <?php echo $_SESSION['USERNAME'];?></h1>
                    <p class="lead fw-normal text-white-50 mb-0">Je kan maar 1 broodje per keer bestellen</p>
                </div>
            </div>
        </header>
        <?php
        } else {
        ?>
                <!-- Header-->
                <header class="bg-dark py-5">
            <div class="container px-4 px-lg-5 my-5">
                <div class="text-center text-white"> <!--het werkt-->
                    <h1 class="display-4 fw-bolder">Goedemorgen, Gast</h1>
                    <p class="lead fw-normal text-white-50 mb-0">Je kan maar 1 broodje per keer bestellen</p>
                </div>
            </div>
        </header>
        <?php } ?>
        <!--miscchien dit toch in een whileloop gooien dat zal ook de code korter maken-->
        <!-- Section-->
        <button onclick="topFunction()" id="myBtn" title="Go to top"></button> 
        <?php 
        include "config.php";
        $sql  = 'SELECT * FROM broodjes';
        $stmt = $conn->prepare($sql); 
        $stmt->execute();
        $result = $stmt->get_result(); // get the mysqli result
        
        while($row = $result-> fetch_assoc()){
            //  $_SESSION['basket'] = array(); 
            //echo $row['broodnaam'];
            echo '        <section class="py-5">
            <div class="container px-4 px-lg-5 mt-5">
                <div class="row gx-4 gx-lg-5 row-cols-2 row-cols-md-3 row-cols-xl-4 justify-content-center">
                    <div class="col mb-5">
                        <div class="card h-100">
                            <!-- Product image dit kan later nog wel-->
                            <div class="fw-image">
                                <img class="card-img-top" src="https://dummyimage.com/450x300/dee2e6/6c757d.jpg" alt="..." />
                            </div>
                            <!-- Product details-->
                            <div class="card-body p-4">
                                <div class="text-center">
                                    <div class="test1">
                                    <input type="hidden" name="broodjes_ID" value=', $row['broodjes_ID'] , '/>
                                    </div>
                                    <!-- Product name-->
                                    <div class="test3">
                                        <input type="hidden" name="broodnaam" value=', $row['broodnaam'] , '/>
                                        <h5 class="fw-bolder">'.$row['broodnaam']. '</h5>
                                    </div>
                                    <!-- Product price-->
                                    <div class="test2">
                                        <input type="hidden" name="broodnaam" value=', $row['prijs'] , '/>
                                        <h3> Prijs:  </h3>   <h3 class="fw-price"> €'.$row['prijs']. '</h3><br>
                                    </div>
                                    <!--voorraad--> 
                                    '; if($row['voorraad'] == 0){
                                        echo '
                                        <h3 class="fw-voorraad" style="color: red;"> uitverkocht</h3><br>
                                    '; }else{ 
                                        echo ' 
                                        Voorraad: '.$row['voorraad'].'<br>
                                        </div>
                                        </div>
                                        <!-- Product actions-->
                                        
                                        <form action="cart.php?broodjes_ID='. $row['broodjes_ID'].'" method="post" name="broodjes"  value"<?php echo htmlentities(serialize($_SESSION["basket"])); ?> 
                                            <div class="card-footer p-4 pt-0 border-top-0 bg-transparent">
                                                <div class="text-center"><button class="btn btn-outline-dark mt-auto shop-item-button" type="submit" name="add_to_cart">Bestellen</button></div>
                                            </div>
                                        </form>
                                    '; } 
                                    //  if (isset($_POST['add_to_cart'])) {
                                        
                                        $_SESSION['basket'][] = $row['broodjes_ID'];
                                        //$_SESSION['basket'] = array_push($_SESSION['basket'], $row['broodjes_ID']);
                                    //     // echo $_SESSION['basket'][0];
                                    //     // $array = $_SESSION['basket'];
                                    //     // if (is_array($array) || is_object($array)){
                                    //     //         foreach ($array as $key => $value) {
                                                    
                                    //     //             echo "{$key} => {$value} ";
                                    //     //             print_r($array);
                                            //}
                                    //     // }else{
                                            
                                    //     // }
                                    //     //int(1) betkenend dat hij telt hoeveel er dus in zijn array zit.
                                        var_dump($_SESSION['basket']);
                                        
                            
                                    //  }
                        echo '</div>
                    </div>
                </div>
            </div>
        </section>';                           

        
        }
        var_dump($_SESSION['basket']);
        ?>
        
        <!-- Footer-->
        <?php include "footer.php";?>
        <!-- Bootstrap core JS-->
        <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
        <!-- Core theme JS-->
        <script src="js/scrolltotop.js"></script>
    </body>
</html>



PHP
<pre><?php 
session_start();
error_reporting(E_ALL);
ini_set('display_errrors', '1');
// session_destroy();
?>
<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="utf-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no" />
        <meta name="description" content="" />
        <meta name="author" content="" />
        <title>Cart</title>
        <!-- Favicon-->
        <link rel="icon" type="image/x-icon" href="assets/favicon.ico" />
        <!-- Bootstrap icons-->
        <link href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.5.0/font/bootstrap-icons.css" rel="stylesheet" />
        <!-- Core theme CSS (includes Bootstrap)-->
        <link href="css/styles.css" rel="stylesheet" />
        <link href="css/stylecart.css" rel="stylesheet" />
        <script src="js/scripts.js" async></script>

    </head>
    <style>
    body {
        font-family: Arial, Helvetica, sans-serif;
        font-size: 20px;
    }

    </style>
<body>
<!--navbar-->
<a class="back" href="index.php"> </a>
<?php 
include "config.php";
//print_r($_SESSION['basket']);
        ?>
        <div class="text-center" style="font-size: 100px;">🛍</div>
        <h2 class="text-center">Winkelmandje</h2><br>
        <section class="container content-section">
            <!-- <h2 class="section-header">CART</h2> -->
            <div class="cart-row">
                ITEM
                PRICE
                QUANTITY 
            </div>  
            <?php 
            print_r($_SESSION['basket']);
             $broodjes_ID = $_GET['broodjes_ID'];
             //print_r($_SESSION['basket']);
             
            //var_dump($_SESSION['basket']);
             //$count = 1; // count basket puts 3 times the same item in the shopping cart
             //print_r($count);
             //echo $count;
            //  if($count > 0){
                 
                //  for($i = 0; $i<$count; $i++){
                     // var_dump($_SESSION['basket']);
                     foreach($_SESSION['basket'] as $key => $value){
                         
                         //echo "Key = $key; value = $value; <br>";
                         $sql = "SELECT broodjes_ID, broodnaam, prijs FROM broodjes WHERE broodjes_ID=$value";
                         $stmt = $conn->prepare($sql); 
                         $stmt->execute();
                         $result = $stmt->get_result();
                         while($row = $result-> fetch_assoc()){
                            $sum = 0;
                            echo '<div class="cart-items">';
                            echo '<div class="cart-row">';
                            echo '<div class="cart-item cart-column">';
                             echo $row['broodnaam'];
                             
                            //  echo $row['broodjes_ID'];
                            echo "</div>";
                            echo '<div class="cart-item cart-column">';
                             echo $row['prijs'];
                             echo "</div>";
                             echo "</div>";
                             echo "</div>";
                             $sum = $sum + $row['prijs']; 
                         }

                         
                     } 
                     ?> <br />
                                            

                         <!--     } -->
                     
                     
                         <!--  } -->
                        
                   
                
                        
                    
               
                    <div class="cart-total">
                        <?php   echo $sum;?>
                    </div>
                    <br/>
                <!-- 
                <div class="cart-total">
                    ^__strong class="cart-total-title">Total
                     € 0
                </div>
             -->




        </section>
                </body>



What I have tried:

I have been looking on the internet for a while but the moment you ask about shopping carts you get javascript stuff. I don't wanna use java script I want to use array's
Posted
Updated 14-Jan-22 3:40am

Hi,

I do have lots of PHP/MySQL experience but never implemented a basket/cart, so I can't judge your overall approach. However I do have several comments:

1.
General comment: too much effort and code have been spent early on presentation while the code is not yet performing essential functions correctly. My advice is: get it to work first (with as few lines of code as possible, no bootstrap, no styles) and only when all technical problems have been solved then take care of layout, style, and minor details.

2.
In your statement
PHP?HTML?
<form action="cart.php?broodjes_ID='. $row['broodjes_ID'].'" method ...

(a) you are mixing HTML and PHP without using <?php and ?>
(b) you are missing an equal sign after "value"
(c) however value is not an official parameter for a form; what happened?
(d) you are passing broodjes_ID as a URL parameter while specifying a post method. I'm not sure that will ever work. Normal way of passing data with forms AFAIK is by using hidden fields. Something like
PHP
$brID=$row['broodjes_ID'];
echo "<input type='hidden' name='brID' value='$brID'>";


3.
You have
PHP
$_SESSION['basket'][] = $row['broodjes_ID'];

inside the while loop that iterates all broodjes; this means 'basket' is an array and one broodje is to be appended to the array, so I'm not surprised you are always ordering one of everything.

4.
Suggestion:
clean up your code, remove code that got commented out, do keep comments that explain what you intend to do and why you are doing it in the chosen way. Also take care of indentation. Clean code helps in understanding what is going on.
 
Share this answer
 
v4
Comments
Rebecca2002 14-Jan-22 5:52am    
I understand the styling and that it might be messy but I have tried to do this already for a very long time and I had to show at least some results so I decided to style the page. this is also easier for me to see when the code does something. but to the real problem:
I have tried to put the $_SESSION['basket'][] =$row['broodjes_ID']; outside the while loop but then I guess it just kinda skips it? like it doesn't add anything anymore into my array. I also want to say that your comment 2 a is not true. I did wrap it into php tags. its more like <php echo="" "<form="" action="cart.php?broodjes_ID='. $row['broodjes_ID'].'" method="POST" name="broodjes" value="<?php echo htmlentities(serialize($_SESSION[" basket"]));="" ?="">

Bestellen

"; ?>
Here is a simple cart implementation.
It uses a single PHP file, no javascript and no session! (Normally one would use javascript so adding/removing an item would not request a new page from the server)

It mimics a database table by first creating an array of items using a little class.

Usage:
- Put all the code in a file "cart1.php", then browse that file, it should work straight away.
- Change withDebug to true to see what is going on inside.

HTML
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<meta name='Author' content='Luc Pattyn - Perceler' />
<meta name="description" content="Simple cart demo (without javascript)">
<title>Cart demo</title>
<style>
body   {font-family:verdana; font-size: 13px}
th,td  {padding: 5px 10px; text-align: center}
.bold  {font-weight:bold}
.debug {color: magenta}
</style>
</head>
<body>
<?PHP
	error_reporting(E_ALL);
	ini_set('display_errrors', '1');
	$currency="&"."euro;";	// string was split to avoid CodeProject bug
	$withDebug=false;
	// show all parameters
	debug("REQUEST: ");
	if ($withDebug) print_r($_REQUEST);
				
	$items=getAllKnownItems();
	// if a basket is present, use it to initialize the quantities
	if (isset($_REQUEST['basket'])) {
		$basket=$_REQUEST['basket'];
		debug("old basket=$basket");
		if ($basket!="") {
			$basket=explode(".", $basket);
			foreach($basket as $ID) $items[$ID]->Quantity++;	// increment quantity
		}
		// now execute the requested changes to quantities
		if (isset($_REQUEST["incr"])) {
			$ID=$_REQUEST["ID"];
			debug("going to increment item $ID");
			$items[$ID]->Quantity++;
		}	 
		if (isset($_REQUEST["decr"])) {
			$ID=$_REQUEST["ID"];
			debug("going to decrement item $ID");
			$item=$items[$ID];
			if ($item!=null && $item->Quantity>0) $item->Quantity--;
		}	 
	} else {
		debug("no basket");
	}	
	
	// create the string describing current basket (just concatenate ID values)
	// will be used by a <form> if and when user wants to change quantities
	// also calculate total cost
	$basket=array();
	$totalQuantity=0;
	$totalPrice=0;
	foreach($items as $item) {
		$ID=$item->ID;
		$quantity=$item->Quantity;
		$price=$item->Price;
		for($i=0; $i<$quantity; $i++) {
			$basket[]=$ID;
			$totalQuantity++;
			$totalPrice+=$price;
		}
	}
	$basket=implode(".", $basket);	// convert array to string
	debug("new basket=$basket");
	$basketField="<input type='hidden' name='basket' value='$basket' />";
	
	// display the menu
	html("<table border='1'>");
	html("  <tr><th>Quantity</th><th>Item</th><th>Unit Price</th><th>Edit Order</th></tr>");
	foreach($items as $item) {
		$ID=$item->ID;
		$quantity=$item->Quantity;
		$descr=$item->Descr;
		$price=$item->Price;
		$btn="<form action='cart1.php' method='post'>".
			"<input type='submit' name='incr' value='Plus 1' /> ".	// button
			"<input type='submit' name='decr' value='Minus 1' />".	// button
			"<input type='hidden' name='ID' value='$ID'>".	// current item
			$basketField.									// basket content
			"</form>";
	html("  <tr><td>$quantity</td><td>$descr</td><td>$price $currency</td>");
	html("      <td>$btn</td></tr>");
	}
	html("</table>");
	if ($totalQuantity!=0) {
		html("<p class='bold'>Total: $totalQuantity items for $totalPrice $currency</p>");
		html("<p class='bold'>Smakelijk !</p>");
		html("<form action='cart1.php' method='post'>".
			"<input type='submit' name='clr' value='Clear all' />".	// button
			"</form>"); // no code required, we simply don't pass a basket!!!
	}
	
	function html($s) {
		echo "$s\n";
	}
	
	function debug($s) {
		global $withDebug;
		if ($withDebug) echo "<p class='debug'>$s</p>";
	}
	
	function getAllKnownItems() {
		// create the array containing all menu items
		// (would normally come from a database table,
		// we fake it here by filling an array)
		$items=array();
		$items[1]=new Item(1, "Broodje Hesp", 1.01);
		$items[12]=new Item(12, "Broodje Kaas", 1.12);
		$items[23]=new Item(23, "Becky Special", 1.23);
		$items[27]=new Item(27, "Glas Karnemelk", 1.27);
		return $items;
	}
		
	class Item {
		var $ID;
		var $Quantity;
		var $Descr;
		var $Price;
		function __construct($ID, $descr, $price) {
			$this->ID=$ID;
			$this->Quantity=0;
			$this->Descr=$descr;
			$this->Price=$price;
		}
	}
?>
</body>
</html>


EDIT: some code cleanup
 
Share this answer
 
v6
Comments
Rebecca2002 18-Jan-22 3:23am    
this is a lot of code but how will I add the order and the order items into my db? and how will I use the items from my db?? I know that I have to change something in the function getAllKnownItems() but I don't know what
Luc Pattyn 18-Jan-22 8:44am    
To get items from the database, you need an SQL statement (SELECT * FROM table) and a while loop; you have done so already. Each iteration of the loop would give you the details of one broodje, which you can use to create a new Item(...) which you add to $items (using the right ID!).

To place an order, it depends on how you see it. One way would be like this:
- add an "Order" button similar to the "Clear All" button;
- and add some code that checks the button is pressed (similar to how the incrment/decrement buttons are handled) and call a new function that iterates all items and inserts the ones with non-zero quantity; it basically is the counterpart of getAllKnownItems(), with an SQL INSERT statement inside the loop.

All of this is basic PHP stuff. My code was meant to show you something that works (and deals with quantities). Use it any way you want, expand it, or drop it. It is your job after all.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900