keeping items in cart when click add item to cart - php

I'm trying to create a shopping cart based on an array but I can't seem to add more then one item into my cart. can someone help me??
above you see the array so it does continue to put things into my array but it only shows one item what am I doing wrong? have been trying to fix this for 2 months now
// code for the shopping cart
<?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-size: 20px;
}
</style>
<body>
<a class="back" href="index.php"> <i class="bi bi-arrow-left-circle-fill bi-5x"></i></a>
<?php
include "config.php";
print_r($_SESSION['basket']);
array_push($_SESSION['basket'], $_GET['broodjes_ID']);
// oke het is neit geweldig maar het laat iets s
?>
<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">
<span class="cart-item cart-header cart-column">ITEM</span>
<span class="cart-price cart-header cart-column">PRICE</span>
<!-- <span class="cart-quantity cart-header cart-column">QUANTITY</span> -->
</div>
<?php
$broodjes_ID = $_GET['broodjes_ID'];
//onthouden van vorige get request
//$count = count($_SESSION['basket']); // count basket puts 3 times the same item in the shopping cart
if($_SESSION['basket'] > 0){
for($i = 0; $i<$_SESSION['basket']; $i++){
//$basket = $_SESSION['basket'][$i];
$sql = "SELECT broodjes_ID, broodnaam, prijs FROM broodjes WHERE broodjes_ID = ?";
// uitvoeren, resultaat tonen in tabel.
$stmt = $conn->prepare($sql);
$stmt->bind_param("i", $broodjes_ID);
$stmt->execute();
$result = $stmt->get_result(); // get the mysqli result
//while loop zorgt er volgens mij voor dat hij blijft optellen
if($row = $result-> fetch_assoc()){
$sum = 0;
echo '<div class="cart-items">';
echo '<div class="cart-row">';
echo '<div class="cart-item cart-column">';
echo '<span class="cart-item-title">'. $row['broodnaam'] . '</span>';
echo '</div>';
echo '<span class="cart-price cart-column"> €'. $row['prijs'] . '</span>';
echo '</div>';
echo '</div>';
$sum = $row['prijs'];
break;
}
}
?>
<div class="cart-total">
<strong class="cart-total-title">Total</strong>
<span class="cart-total-price"> € <?php echo $sum;?></span>
</div>
<?php
}else{
echo 'mandje is leeg.';
?>
<div class="cart-total">
<strong class="cart-total-title">Total</strong>
<span class="cart-total-price"> € 0</span>
</div>
<?php
}
?>
<div class="text-center">
<button class="btn btn-outline-primary" type="button">PURCHASE</button>
</div>
</section>
</body>
this is the code for the store page
<?php
session_start();
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">Shop in style</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">Shop in style</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">Add to cart</button></div>
</div>
</form>
'; }
echo '</div>
</div>
</div>
</div>
</section>';
if (isset($_POST['add_to_cart'])) {
$_SESSION['basket'] = array();
//$_SESSION['basket'][] = $row['broodjes_ID'];
$_SESSION['basket'] = array_push($_SESSION['basket'], $row['broodjes_ID']);
}
}
?>
<!-- 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>

it seems like you are using wrong conditions for your loop
instead of $i<$_SESSION['basket'] use $i<count($_SESSION['basket'])
same problem for you if condition
count() gives the count of number of element in the array
Here is the fixed code
<?php
$broodjes_ID = $_GET['broodjes_ID'];
//onthouden van vorige get request
//$count = count($_SESSION['basket']); // count basket puts 3 times the same item in the shopping cart
//use count
if(count($_SESSION['basket']) > 0){
//use count
for($i = 0; $I<count($_SESSION['basket']); $i++){
//$basket = $_SESSION['basket'][$i];
$sql = "SELECT broodjes_ID, broodnaam, prijs FROM broodjes WHERE broodjes_ID = ?";
// uitvoeren, resultaat tonen in tabel.
$stmt = $conn->prepare($sql);
$stmt->bind_param("i", $broodjes_ID);
$stmt->execute();
$result = $stmt->get_result(); // get the mysqli result
//while loop zorgt er volgens mij voor dat hij blijft optellen
if($row = $result-> fetch_assoc()){
$sum = 0;
echo '<div class="cart-items">';
echo '<div class="cart-row">';
echo '<div class="cart-item cart-column">';
echo '<span class="cart-item-title">'. $row['broodnaam'] . '</span>';
echo '</div>';
echo '<span class="cart-price cart-column"> €'. $row['prijs'] . '</span>';
echo '</div>';
echo '</div>';
$sum = $row['prijs'];
break;
}
}
?>

Related

array_push while loop shopping cart item into basket without javascript

hello I want to add a cart item into a cart by using a button. For this I want to array_push this into my array. And then show that array into my cart. this is not what is happening right now:
right now it shows the last item from the while loop in the shopping cart and thats not what I want.
I want that if the user pressed the add_to_cart button then array_push this broodjes_ID, broodnaam, and prijs into the cart. what am I doing wrong?
index.php <- the shop
<!-- session_start(); session has already started -->
<?php
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">Shop in style</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">Shop in style</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">
<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">Add to cart</button></div>
</div>
</form>
'; }
echo '</div>
</div>
</div>
</div>
</section>';
}
?>
<!-- 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>
cart.php
<!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>
<?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();
if(isset($_POST['add_to_cart'])){
array_push($_SESSION['basket'], $row['broodjes_ID'], $row['broodnaam'], $row['prijs']);
}
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">
<span class="cart-item cart-header cart-column">ITEM</span>
<span class="cart-price cart-header cart-column">PRICE</span>
<span class="cart-quantity cart-header cart-column">QUANTITY</span>
</div>
<?php
// query maken waarbij wij naam en prijs ophalen van de ids.
$count = count($_SESSION['basket']);
if($count > 0){
$sum = 0;
for($i = 0; $i<$count; $i++){
$basket = $_SESSION['basket'][$i];
$sql = "SELECT broodjes_ID, broodnaam, prijs FROM broodjes WHERE broodjes_ID = ?";
// uitvoeren, resultaat tonen in tabel.
$stmt = $conn->prepare($sql);
$stmt->bind_param("s", $basket);
$stmt->execute();
$result = $stmt->get_result(); // get the mysqli result
while($row = $result-> fetch_assoc()){
echo '<div class="cart-items">';
echo '<div class="cart-row">';
echo '<div class="cart-item cart-column">';
echo '<span class="cart-item-title">'. $row['broodnaam'] . '</span>';
echo '</div>';
echo '<span class="cart-price cart-column"> €'. $row['prijs'] . '</span>';
echo '</div>';
echo '</div>';
$sum += $row['prijs'];
}
}
?>
<div class="cart-total">
<strong class="cart-total-title">Total</strong>
<span class="cart-total-price"> € <?php echo $sum;?></span>
</div>
<?php
}else{
echo 'mandje is leeg.';
?>
<div class="cart-total">
<strong class="cart-total-title">Total</strong>
<span class="cart-total-price"> € 0</span>
</div>
<?php
}
?>
<div class="text-center">
<button class="btn btn-primary btn-purchase" style="margin: 5%;" type="button">PURCHASE</button>
</div>
</section>

How to create a edit profile page for users with PHP?

I've created a page but I can´t put the Save button working and regardless of the user I enter with, it appears the same user information for them all.
I think it's a loop problem but I'm not sure what it is.
<?php
require_once('LoginConfig.php');
session_start();
if(isset($_SESSION["email"])){
$user_check = $_SESSION["email"];
$result = $connect->prepare("SELECT * FROM users WHERE user_email = :usercheck");
$result->execute(array(":usercheck"=>$user_check));
$row = $result->fetch(PDO::FETCH_ASSOC);
}else
{
header("location:UsersLogin.php");
}
?>
<!DOCTYPE html>
<html lang="PT-pt">
<head>
<title> Editar Perfil - JamJam </title>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link href='https://fonts.googleapis.com/css?family=Source+Sans+Pro:700, 600,500,400,300' rel='stylesheet' type='text/css'>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.5.0/css/font-awesome.min.css">
<link rel="stylesheet" href="http://code.ionicframework.com/ionicons/2.0.1/css/ionicons.min.css">
<link rel="stylesheet" type="text/css" href="assets/css/style-menu.css">
<link rel="stylesheet" type="text/css" href="assets/css/style-articlelist2.css">
<script src="https://kit.fontawesome.com/8a368d3752.js"></script>
<script src="https://code.jquery.com/jquery-2.2.0.min.js"></script>
<script src="https://code.highcharts.com/highcharts.js"></script>
<script src="https://code.highcharts.com/modules/data.js"></script>
<script src="assets/js/main.js"></script>
<style>
</style>
</head>
<body>
<div class="header">
<div class="logo">
<i style='font-size:24px' class='fas'>ď–Ź</i>
<span style='font-size:24px'>JamJam</span>
</div>
<span></span>
</div>
<div class="side-nav">
<div class="logo">
<i style='font-size:24px; color:rgb(0,255,0)' class='fas'>ď–Ź</i>
<span style='font-size:24px'>JamJam</span>
</div>
<nav>
<ul>
<li>
<a href="UsersMenu.php">
<span><i style='color:rgb(0,255,0)' class="fas fa-home"></i></span>
<span>Página Inicial</span>
</a>
</li>
<li class="active">
<a href="UsersProfile.php">
<span><i style='color:rgb(0,255,0)' class="fa fa-user"></i></span>
<span>Perfil</span>
</a>
</li>
<li>
<a href="UsersArticleList.php">
<span><i style='color:rgb(0,255,0)' style='font-size:16px' class='fas'>&#xf001</i></span>
<span>MĂşsicas</span>
</a>
</li>
<li>
<a href="Logout.php">
<span><i style='color:rgb(0,255,0)' class="fas fa-sign-out-alt"></i></span>
<span>Logout</span>
</a>
</li>
</ul>
</nav>
</div>
<div class="main-content">
<div class="title">
Editar Perfil
</div>
<div class="main">
<div class="widget" style="lex-basis: 98%; height: 750px;">
<?php
if(isset($_SESSION["email"])){
$result = $connect->prepare("SELECT user_id, user_name, user_bio, user_local, user_image FROM users");
$result->bindParam(':userid', $id);
$result->execute();
$row = $result->fetch()
?>
<form style="text-align: left; margin: 15px; " action="<?php echo $_SERVER['PHP_SELF']; ?>" method="POST">
<input $id="user_id" name="user_id" type="hidden" value= "<?php echo $row['user_id']; ?>">
<div >
<label for="username">Nome:</label><br>
<input type="text" name="username" value="<?php echo $row['user_name']; ?>">
</div>
<div>
<label for="bio">Bio:</label>
<br>
<textarea type="text" class="textarea" name="bio" rows ="4"><?php echo $row['user_bio']; ?></textarea>
</div>
<div>
<label for="local">SĂ­tio onde vive:</label><br>
<input type="text" name="local" value="<?php echo $row['user_local']; ?>">
</div>
<div>
<label for="image">Foto de perfil atual:</label><br>
<img src="<?php echo 'images/' . $row['user_image']; ?>">
</div>
<div>
<br> <form action="upload.php" method="post" enctype="multipart/form-data">
<lable for="image">Selecionar nova foto de perfil:</lable><br>
<input type="file" name="fileToUpload" id="fileToUpload">
</form>
</div>
<div style="text-align: left; margin: 10px;" class="box">
<button style="float: left;" class="saveButton" type="submit">Guardar</button>
<a style="float: right;" class="cancelButton" href="UsersProfile.php">Cancelar</a>
</div>
</form>
<?php
}
?>
</div>
</div>
</body>
</html>

Removing one item from cart removes everything instead

I have a implemented a shopping cart function on my project website by following this guide video on YT https://www.youtube.com/watch?v=eAK8uYtNTy4&t=3528s and I am able to add items to the shopping cart and remove items(kind of). However the remove function is very odd indeed,because it allows me to remove the item but when I clicked on it it also removes other items that is currently in the cart as well...
Here are my codes for the cart (cart.php)
<?php
session_start();
require_once ("conn.php");
require_once ("component.php");
if (isset($_POST['remove'])){
if ($_GET['action'] == 'remove'){
foreach ($_SESSION['cart'] as $key => $value){
if($value["ID"] == $_GET['game_ID']){
unset($_SESSION['cart'][$key]);
echo "<script>alert('Product has been Removed...!')</script>";
echo "<script>window.location = 'cart.php'</script>";
}
}
}
}
?>
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Cart</title>
<link rel="icon" href= "images/logoonly.png" type="image/jpg" sizes="16x16">
<link rel="stylesheet" href="css/style.css">
<link rel="stylesheet" href="css/cart.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
<script src="js/sticky.js"></script>
<script src="https://kit.fontawesome.com/ac84272c35.js" crossorigin="anonymous"></script>
</head>
<body>
<!-- Navigation -->
<navbar>
<section class="navbar-section" style="background-color: #252525; box-shadow: 0px 2px 6px black;">
<div class="navbar-div">
<div class="navbar-div-logo">
<a href="index.html">
<img href="index.html" class="logo-pic" src="images/logoonly.png" alt="">
<img class="logo-name" src="images/logonameonly.png" alt="">
</a>
</div>
<ul class="navbar-ul-links">
<li> <a class="navbar-a-links" href="index.html">home</a> </li>
<li> <a class="navbar-a-links" href="store.php">store</a> </li>
<li> <a class="navbar-a-links" href="news.html">news</a> </li>
<li> <a class="navbar-a-links" href="about.html">about</a> </li>
</ul>
<div class="navbar-div-cart-login">
<i class="fas fa-shopping-bag"></i>
<a class="login navbar-a-links" href="login.html">login</a>
</div>
</div>
</section>
</navbar>
<!-- /Navigation -->
<!-- Main Content -->
<?php
$total = 0;
if (isset($_SESSION['cart'])){
$ID = array_column($_SESSION['cart'], 'game_ID');
include("conn.php");
$result = mysqli_query($con,"Select * from games where games.game_status = 1");
while($row = mysqli_fetch_array($result)){
foreach ($ID as $game_ID){
if ($row['game_ID'] == $game_ID){
cartElement( $row['game_name'],$row['game_price'], $row['game_ID']);
$total = $total + (int)$row['game_price'];
}
}
}
}else{
echo "<h5>Cart is Empty</h5>";
}
?>
</section>
<!-- /Main Content -->
<!-- Footer -->
<footer>
<section class="footer-section" style="background-color: black;">
</section>
</footer>
<!-- /Footer -->
<script src="js/modal.js"></script>
<!-- Animate Show Panel -->
<script type="text/javascript">
function show(elementId) {
document.getElementById("personal-info").style.display = "none";
document.getElementById("acc-info").style.display = "none";
document.getElementById(elementId).style.display = "flex";
}
</script>
<!-- /Animate Show Panel -->
</body>
</html>
here are the components for the cart to display the items. (component.php)
<?php
function component($game_name, $game_price, $game_ID){
$element = "
<form action=\"store.php\" method=\"post\">
<div class=\"newrelease\">
<div class=\"special-offer-description-div\">
<h5 name=\"game_name\">$game_name</input></h5>
<button type=\"submit\" class=\"purchase\" name=\"add\">Add To Cart</button>
<input type='hidden' name='game_ID' value='$game_ID'>
<div class=\"price-div\">
<h6>- 85%</h6>
<p class=\"strikethrough\" name=\"game_price\">RM$game_price</p>
</div>
</div>
</div>
</form>
";
echo $element;
}
function cartElement($game_name, $game_price, $game_ID){
$element = "
<form action=\"cart.php?action=remove&id=$game_ID\" method=\"post\">
<section class=\"cart-section\">
<div class=\"block\"></div>
<div class=\"cart-div\">
<h1>$game_name</h1>
<!-- Cart Games -->
<div class=\"cart-items-div\">
<div class=\"description-div\">
<div class=\"description\">
<!-- Game Name -->
<h2 class=\"game-title\"></h2>
<!-- Game Description -->
<div class=\"d\">
<div class=\"details\">
<h2>overall reviews:</h2>
<h2>release date:</h2>
</div>
<div class=\"game-details\">
<h2 style=\"color: #407AD3;\">very positive</h2>
<h2>8 aug, 2018</h2>
</div>
</div>
<!-- Game Specification -->
<div class=\"compatibility\">
<i class=\"fab fa-windows\"></i>
<i class=\"fab fa-apple\"></i>
<i class=\"fab fa-linux\"></i>
</div>
</div>
<div class=\"button-div\">
<!-- Remove Game From Cart Button -->
<button type=\"submit\" class=\"btn btn-danger mx-2\" name=\"remove\"><i class=\"fas fa-trash-alt\" style=\"color: #FF4444\" ></i> </button>
<!-- Purchase Game -->
<button class=\"purchase\" input type=\"text\" value=\"1\">Purchase</button>
<!-- Price -->
<h3 style=\"border-right: none;\">$game_price</h3>
</div>
</div>
</div>
</form>
";
echo $element;
}

Hide and show button based on user SESSION in php foreach loop

Im trying to not show the remove button to the users that did not uploaded image to website, and I want the remove button be shown only for the user that uploaded a specific image.
The problem is, it is in foreach loop, I tried with
if($user_id == $_GET['id']
but it show every button, but when I put
if($user_id != $_GET['id'])
all button disappear.
This is the button I would like to show/hide
<?php
require('dbconfig.php');
if(!$user->is_loggedIn()) {
$user->Redirect('index.php');
}
$user_id = $_SESSION['user_session'];
$stmt = $db_conn->prepare("SELECT * FROM users WHERE user_id=:user_id");
$stmt->execute(array(":user_id"=>$user_id));
$userRow=$stmt->fetch(PDO::FETCH_ASSOC);
// print_r($userRow);
if(isset($_POST['ok'])) {
$folder = "/Library/WebServer/Documents/Website/uploads/";
$image = $_FILES['image']['name'];
$path = $folder . $image ;
$target_file=$folder.basename($_FILES["image"]["name"]);
$imageFileType=pathinfo($target_file,PATHINFO_EXTENSION);
$allowed=array('jpeg','png' ,'jpg'); $filename=$_FILES['image']['name'];
$ext=pathinfo($filename, PATHINFO_EXTENSION);
if(!in_array($ext,$allowed)) {
echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
} else {
$success = "Image uploaded successfully";
move_uploaded_file( $_FILES['image'] ['tmp_name'], $path);
$stmt = $db_conn->prepare("INSERT INTO images (img, user_id) VALUES (:image, :user_id)");
$stmt->bindparam(":image",$image);
$stmt->bindparam(":user_id",$user_id);
$stmt->execute();
}
}
$subjects = $db_conn->prepare("SELECT img FROM images");
$subjects->setFetchMode(PDO::FETCH_ASSOC);
$subjects->execute();
$stmt = $db_conn->prepare("SELECT user_id FROM images");
$stmt->execute();
$nesto=$stmt->fetchAll(PDO::FETCH_ASSOC);
echo '<pre>';
print_r($nesto);
echo '</pre>';
// echo $nesto['user_id'];
$ids = $_GET['id'];
?>
<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="Mark Otto, Jacob Thornton, and Bootstrap contributors">
<meta name="generator" content="Jekyll v4.0.1">
<title>Management</title>
<!-- Bootstrap core CSS -->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" integrity="sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk" crossorigin="anonymous">
<style>
.bd-placeholder-img {
font-size: 1.125rem;
text-anchor: middle;
-webkit-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
}
#media (min-width: 768px) {
.bd-placeholder-img-lg {
font-size: 3.5rem;
}
}
</style>
<!-- Custom styles for this template -->
<link href="album.css" rel="stylesheet">
</head>
<body>
<header>
<div class="navbar navbar-dark bg-dark shadow-sm">
<div class="container d-flex justify-content-between">
<a href="#" class="navbar-brand d-flex align-items-center">
<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="2" aria-hidden="true" class="mr-2" viewBox="0 0 24 24" focusable="false"><path d="M23 19a2 2 0 0 1-2 2H3a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h4l2-3h6l2 3h4a2 2 0 0 1 2 2z"></path><circle cx="12" cy="13" r="4"></circle></svg>
<strong>Pictures</strong>
</a>
Home
Profile
</div>
</div>
</header>
<main role="main">
<section class="jumbotron text-center">
<div class="container">
<h1>Shared Gallery</h1>
<p class="lead text-muted"><?php print($userRow['user_name']); ?></p>
<p>
<p><?php echo $success; ?></p>
<!-- Upload Image Form -->
<div>
<form method="POST" enctype="multipart/form-data">
<input type="file" name="image" />
<input type="submit" name="ok"/>
</form>
</div>
<!-- End Upload Image Form -->
Logout
</p>
</div>
</section>
<div class="album py-5 bg-light">
<div class="container">
<div class="row">
<!-- START -->
<?php foreach($subjects as $subject) { ?>
<div class="col-md-4">
<div class="card mb-4 shadow-sm">
<img src="uploads/<?php echo $subject['img']; ?>" class="bd-placeholder-img card-img-top" width="100%" height="225" focusable="false"/>
<div class="card-body">
<p class="card-text">
<ul>
<li>Username</li>
<li>Email</li>
<li>Address</li>
</ul>
</p>
<div class="d-flex justify-content-between align-items-center">
<div class="btn-group">
THIS IS THE BUTTON I WANT TO SHOW AND HIDE
<button type="button" class="btn btn-sm btn-outline-secondary">Remove</button>
THIS IS THE BUTTON I WANT TO SHOW AND HIDE
</div>
<small class="text-muted">9 mins</small>
</div>
</div>
</div>
</div>
<?php } ?>
<!-- END -->
</div>
</div>
</div>
</main>
<footer class="text-muted">
<div class="container">
<p class="float-right">
Back to top
Back to index
</p>
</div>
</footer>
<script src="https://code.jquery.com/jquery-3.5.1.slim.min.js" integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj" crossorigin="anonymous"></script>
<script>window.jQuery || document.write('<script src="/docs/4.5/assets/js/vendor/jquery.slim.min.js"><\/script>')</script><script src="/docs/4.5/dist/js/bootstrap.bundle.min.js" integrity="sha384-1CmrxMRARb6aLqgBO7yyAxTOQE2AKb9GfXnEo760AUcUmFx3ibVJJAzGytlQcNXd" crossorigin="anonymous"></script>
</body></html>
If you change these 2 queries into one query, you would have a resultset with the img and the users id, you can then use that to compare with the user that is logged in
//$subjects = $db_conn->prepare("SELECT img FROM images");
//$subjects->setFetchMode(PDO::FETCH_ASSOC);
//$subjects->execute();
//$stmt = $db_conn->prepare("SELECT user_id FROM images");
//$stmt->execute();
//$nesto=$stmt->fetchAll(PDO::FETCH_ASSOC);
Replace as
$result = $db_conn->query("SELECT img, user_id FROM images");
$subjects = $result->fetchAll(PDO::FETCH_ASSOC);
Then around your button you can do
<?php
// If this user uploaded this image they are allowed to remove it
if ($subject->user_id == $_SESSION['user_session']) :
<button type="button" class="btn btn-sm btn-outline-secondary">Remove</button>
endif;
?>
Big Note
I dont see a session_start() in this code, as you are using $_SESSION you would need one of those right at the top of this script.
I decided to do it this way
This worked for me perfectly.
<!-- START -->
<?php foreach($subjects as $subject) : ?>
<div class="col-md-4">
<div class="card mb-4 shadow-sm">
<img src="uploads/<?php echo $subject['img']; ?>" class="bd-placeholder-img card-img-top" width="100%" height="225" focusable="false"/>
<div class="card-body">
<p class="card-text">
<ul>
<li><?php echo $subject['img_id']; ?></li>
<li><?php echo $subject['user_name']; ?></li>
<li><?php echo $subject['user_email']; ?></li>
<li>Address</li>
</ul>
</p>
<div class="d-flex justify-content-between align-items-center">
<div class="btn-group">
<?php foreach($subject as $val) : ?>
<?php if ($user_id == $_SESSION['user_session'] && $val == $user_id) : ?>
<?php $id = $subject['img_id']; ?>
<form method="POST" action="<?php echo "delete.php?id=" . $subject['img_id']?>">
<!-- <button name="remove" type="button" class="btn btn-sm btn-outline-secondary">Remove</button> -->
<input type="hidden" name="del" value="1" />
<input type="submit" name="del" class="btn btn-sm btn-outline-secondary" value="Remove" />
</form>
<?php endif; ?>
<?php endforeach; ?>
</div>
</div>
</div>
</div>
</div>
<?php endforeach; ?>
<!-- END -->

Convert a PHP "Object" to a SESSION?

I have a {$obj->product_stock} which contains a numeric value - the stock of the product.
How can I convert that {$obj->product_stock} to a SESSION? Here is what I tried...
$_SESSION['product_stock'] = {$obj->product_stock};
Why does it error and how can I get round this?
<?php
session_start();
include_once("config.php");
// Current URL of the Page. cart_update.php redirects back to this URL
$current_url = urlencode($url="http://".$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI']);
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="description" content="">
<meta name="keywords" content="">
<title>Product Page</title>
<?php include("includes/header-includes.php"); ?>
</head>
<body>
<?php include("includes/navigation.php"); ?>
<?php include("includes/basket-warning.php"); ?>
<!-- Products List Start -->
<?php
$ProductID = intval($_REQUEST['ProductID']);
$results = $mysqli->query("SELECT * FROM products where ProductID = '$ProductID';");
if($results) {
$_SESSION['product_stock'] = $obj->product_stock;
echo "STOCK: ". $_SESSION['product_stock'] ."";
$products_item = '<ul class="products">';
// Fetch results, set as object and output HTML
while($obj = $results->fetch_object()) {
$products_item .= <<< EOT
<li class="product">
<form method="post" action="cart_update.php">
<div class="product-content">
<h3>{$obj->ProductName} <strong>(STOCK: {$obj->product_stock}</strong>)</h3>
<div class="product-image" style="background: url({$obj->TypeImage}) no-repeat; background-size: 100%; min-height: 551.328px;">
<div id="carousel-example-generic" class="carousel slide" data-ride="carousel">
<div class="carousel-inner" role="listbox">
<div class="item active"><img src={$obj->TypeImage} class="img-responsive"></div>
<div class="item"><img src={$obj->AlternativeImagesOne} class="img-responsive"></div>
<div class="item"><img src={$obj->AlternativeImagesTwo} class="img-responsive"></div>
<div class="item"><img src={$obj->AlternativeImagesThree} class="img-responsive"></div>
</div>
</div>
</div>
<div class="product-content-cont">
<h4>{$obj->ProductName} - Overview</h4>
<p>{$obj->ProductDescription}</p>
</div>
</div>
<div class="like-what-you-see">
<fieldset>
<label>
<span>Price</span>
{$currency}{$obj->Price}
</label>
<label>
<input type="" size="1" maxlength="2" name="product_qty" value="1" class="form-control" />
</label>
</fieldset>
<input type="hidden" name="ProductCode" value="{$obj->ProductCode}" />
<input type="hidden" name="type" value="add" />
<input type="hidden" name="return_url" value="{$current_url}" />
<button type="submit" class="btn btn-warning">Add</button>
</div>
</form>
</li>
EOT;
}
$products_item .= '</ul>';
echo $products_item;
}
?>
<!-- Products List End -->
<?php include("includes/footer.php"); ?>
</body>
</html>
Your code:
$_SESSION['product_stock'] = $obj->product_stock;
echo "STOCK: ". $_SESSION['product_stock'] ."";
is outside the while loop. Therefore $obj is not yet defined.
Move the code above into the while loop like this
$products_item = '<ul class="products">';
// Fetch results, set as object and output HTML
while($obj = $results->fetch_object()) {
$_SESSION['product_stock'] = $obj->product_stock;
echo "STOCK: ". $_SESSION['product_stock'] ."";
....

Categories