For a school project I am trying to create a shoppingcart with php only with MySQLi. For this I have a catalogue called index.php. In this is a table with the product and after every product there is a button which should add the item to the shoppingcart.
The only problem is that I cannot get the link working properly.
<?php
session_start();
include 'connect.php';
$qry = "select * from products";
$result = mysqli_query($connect, $qry);
echo "<table class='catalogue'>";
echo "<tr><th>ID</th><th>Code</th><th>Name</th><th>Description</th><th>Image</th></th><th>Price</th><th>Buy</th></tr>";
while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
echo "<tr><td>";
echo $row['id'];
echo "</td><td>";
echo $row['product_code'];
echo "</td><td>";
echo $row['product_name'];
echo "</td><td>";
echo $row['product_desc'];
echo "</td><td>";
echo $row['product_img_name'];
echo "</td><td>";
echo $row['price'];
echo "</td><td>";
echo "<input type='submit' value='Add' href='cart.php?id=['id']'/>";
echo "</td></tr>";
}
echo "</table>";
?>
The cart.php looks like this.
<?php
session_start();
require 'connect.php';
require 'item.php';
$result = mysqli_query($connect, 'select * from products where id='.$_GET['id']);
$product = mysqli_fetch_object($result);
if(isset($_GET['id'])){
$item = new Item();
$item->id = $product->id;
$item->name = $product->product_name;
$item->price = $product->price;
$item->quantity = 1;
$_SESSION['cart'][] = $item;
}
echo "<table class='cart'>";
echo "<tr><th>ID</th><th>Name</th><th>Price</th><th>Quantity</th><th>Sub Total</th></tr>";
$cart = unserialize(serialize($_SESSION['cart']));
for($i=0; $i<count($cart); $i++){
echo "<tr><td>";
echo $cart[$i]->id;
echo "</td><td>";
echo $cart[$i]->product_name;
echo "</td><td>";
echo $cart[$i]->price;
echo "</td><td>";
echo $cart[$i]->quantity;
echo "</td><td>";
echo $cart[$i]->price * $cart[$i]->quantity;
echo "</td></tr>";
}
?>
Please forgive any other mistakes you might see, I am rather new to PHP.
select * from products where id='.$_GET['id']opens you to SQL injections. Separate user input from SQL with prepared statements.echo "<a href='cart.php?id=" . $row['id'] . "'>Add</a>";