I'm implementing something similar to a shopping cart - a "my favorites" page for products. Users can click on an "add to favorites" link and add products to a favorites table from which they can view the details of those products at a later time. There's no purchase on the site, thus there's no checkout. I've implemented something that sort of works. However, if i reload the favorites page after adding a new item to the favorites table, the item duplicates i.e. a new row is created with the same item. If i reload 100 times, i'll have 100 rows of the same item. Here's my code:
$cartid .= $_GET['cartid'];//gets id of item on which add to cart was clicked
$delid = $_GET['delid'];//gets id of item on which remove from cart was clicked
$count = 0;
$stmt = $db->prepare("SELECT * FROM tbl_product where id = :cartid ");
$stmt->execute(array(':cartid' => $cartid));
//execute the query and add the resultant data into a session array
$row = $stmt->fetch(PDO::FETCH_ASSOC);
$_SESSION['cartItems'][] = $row;
//deletes an item from the cart/favorites table
foreach($_SESSION['cartItems'] as $key => $products){
if($products['id']==$delid) {
//delete from the array by unsetting the index of that element.
unset( $_SESSION['cartItems'][$key]);
//reload the page to show changes
header('Location:cart-page.php');
}
}
//displaying products
echo '<div class="divisorydiv2" style="height:37px;"></div>';
echo ' <table cellspacing="0" class="product_tab">';
echo ' <tr class="tab_header">';
echo ' <td width="32%">Product(s)</td>';
echo '<td width="17%">Qty</td>';
echo ' <td width="17%">Item Price</td>';
echo '<td width="17%">Client</td>';
echo '<td width="17%"></td>';//this column contains link to delete product
foreach($_SESSION['cartItems'] as $product){
echo '</tr>';
echo ' <td class="product">'.$product['name'].'</td>';
echo'<td class="quantity"><input type="text" value='.$product['quantity'].' class="inputform"/></td>';
echo '<td class="item_price">'.$product['price'].'</td>';
echo '<td class="item_total">'.$product['user'].'</td>';
echo '<td class="item_remove"><a href = "cart-page.php?delid='.$product['id'].'" style="color:red">Remove Product</a></td>';//to delete an item
echo '</tr>';
$count+=$product['price'];
}
echo '</table>';
What's causing this duplication of rows? Thank you.