Kevin G Kevin G - 1 month ago 15
PHP Question

How can I create a shopping cart for ticket sales

There seems to be a problem with my code that i am unable to fix. I am getting errors that i am having trouble with.

The error is:


Undefined index id, undefined variable result, and undefined variable i


How do I fix this?

<?php
session_start();
require 'connect.php';
require 'item.php';
$relult = mysqli_query($link, 'select * from tickets where id='.$_GET['id']);
$product = mysqli_fetch_object($result);
if(isset($_GET['id'])){
$item= new Item();
$item->id = $product->id;
$item->name = $product->game;
$item->price = $product->price;
$item->quantity = 1;
$_SESSION['cart'][] = $item;
}
?>
<table align="center">
<td colspan="11"><h4> Upcoming games 2016/2017</h3> <td>
<tr>
<th>id</th>
<th>game</th>
<th>price</th>
<th>stadium</th>
<th>quantity</th>
<th>Sub Total</th>
</tr>
<?php
$cart = unserialize(serialize($_SESSION['cart']));
for($i-0; $i<count($cart); $i++){
?>
<tr>
<td><?php echo $cart[$i]->id; ?> </td>
<td><?php echo $cart[$i]->game; ?> </td>
<td><?php echo $cart[$i]->price; ?> </td>
<td><?php echo $cart[$i]->stsdium; ?> </td>
<td><?php echo $cart[$i]->quantity; ?> </td>
<td><?php echo $cart[$i]->price * $cart[$i]->quantity; ?> </td>
</tr>

<?php } ?>

</table>
<a href=" buytickets.php">Add more tickets to your cart</a>
</div>

Answer

I'm afraid there are quite a lot of problems here.

  • First, two obvious ones: you have $relult instead of $result on line 5. You have $i-0 instead of $i=0 on line 29.

  • Furthermore, you're performing a query (a non-safe one, have a look at parameter binding with PDO) using $_GET['id'], while you don't appear to be sure this variable will be available: you check on line 8 if it is set, but that check is performed after injecting that unknown value in a query...

  • On line 14 you are presuming that $_SESSION['cart'] is an array, although this array has not been defined before.

  • What's up with $cart = unserialize(serialize($_SESSION['cart']))? If the cart is an array of Item objects, you can simply iterate like so: foreach ($_SESSION['cart'] as $item) { echo $item->id; /*etc*/ }