all_product.php -> list out all the products
cart.php->show items being added to cart.
Every time I click add to cart, it will be added to array and i list out all of them. The result will be something like the following (before using in_array() )
Products that are added to cart, ID -> 4
Products that are added to cart, ID -> 7
Products that are added to cart, ID -> 6
Products that are added to cart, ID -> 5
Products that are added to cart, ID -> 5
Products that are added to cart, ID -> 6
Products that are added to cart, ID -> 4
I use in_array() function to add items to cart only if it exists. So the result will become like the following instead :
Products that are added to cart, ID -> 4
Products that are added to cart, ID -> 7
Products that are added to cart, ID -> 6
Products that are added to cart, ID -> 5
So my question is how to count the total number of times being added for each product; Basically just like each product's quantity.
all_products.php
require 'config.php';
$q = mysqli_query( $db->conn(), "SELECT * FROM product" );
if( mysqli_num_rows($q) > 0 ) { // Check if there are results
while( $row = mysqli_fetch_assoc($q)){
echo '<p> '.$row['product_name'].' | <a href="cart.php?id='.$row['id'].'">Add To Cart!</a></p>';
}
}
cart.php
session_start();
if(isset($_GET['id'])){
if(!isset($_SESSION['cart'])){
$_SESSION['cart']=[]; //Create session 1st time
}
if(isset($_SESSION['cart'])){
if(!in_array($_GET['id'],$_SESSION['cart'])){ //add item only if doesn't exist
$_SESSION['cart'][]=$_GET['id'];
}
foreach($_SESSION['cart'] as $x => $item_added) { // all products being added to cart
echo "Products that are added to cart, ID -> " . $item_added;
echo "<br>";
}
}
}else{ // if user view this page directly without "?id=" , show error
echo "I hate php!";
}
count($_SESSION['cart'])no?$_SESSION['cart'][$_GET['id']] = array('count' => 2, 'somethingelse' => 'test');