Use the session only for IDs and quantities. Fetch names and prices from the database, calculate totals on the server, and escape values before inserting them into HTML.
<?php
$cart = (isset($_SESSION['cart']) && is_array($_SESSION['cart'])) ? $_SESSION['cart'] : [];
$productIds = array_map('intval', array_keys($cart));
if ($productIds) {
$placeholders = implode(',', array_fill(0, count($productIds), '?'));
$stmt = $pdo->prepare("SELECT p_id, p_name, price, img FROM plus2_cart_products WHERE p_id IN ($placeholders)");
$stmt->execute($productIds);
$grandTotal = 0.0;
foreach ($stmt->fetchAll(PDO::FETCH_ASSOC) as $row) {
$id = (int) $row['p_id'];
$qty = (int) ($cart[$id] ?? 0);
$subtotal = $qty * (float) $row['price'];
$grandTotal += $subtotal;
echo htmlspecialchars((string) $row['p_name'], ENT_QUOTES, 'UTF-8');
}
}
?>
The original table-building example is retained below for comparison. In production, also verify stock and pricing again at checkout.
$q="SELECT p_id,price,img,p_name FROM plus2_cart_products";
$result_set = $connection->query($q);
echo "<div class='row'>
<div class='col-md-7 offset-md-1'>
<table class='table my_table'>
<tr class='info'><th>Picture</th> <th> ID</th><th>Name</th><th>Quantity</th><th>Unit Price</th><th>Price</th></tr>";
$price_total=0;
while($row = $result_set->fetch_array(MYSQLI_ASSOC)){
foreach ($_SESSION['cart'] as $key => $val) {
if($row[p_id]=== $_SESSION['cart'][$key]['p_id']){
$price_sub=$_SESSION['cart'][$key]['qty'] * $row[price];
echo "<tr><td ><img src=images/$row[img] class=rounded></td><td>$row[p_id]</td><td >$row[p_name]</td><td>".$_SESSION['cart'][$key]['qty']."</td><td >$row[price] </td><td >$price_sub </td></tr>";
$price_total=$price_total + $price_sub;
}
}
}
$price_tax=round(.1 * $price_total,2);
$price_other = round(0.08 * $price_total,2);
$price_grand=round($price_total + $price_tax + $price_other,2);
To keep it simple we are not adding payment process to this script. You can add like sign up or delivery address to the user and ask them to proceed for payment.
Author & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.