Am having issues with my cart script, i've managed to get it to work by adding an item to the cart, but its not allowing any more items to be added but rather it allows the quantity to be added even when i add another item, its the quantity of the first item that will be increased, here is my code snippet
This my function script that wrietes and generates the cart
<?php
function writeShoppingCart() {
$cart = $_SESSION['cart'];
if (!$cart) {
return '<p>You have no items in your shopping cart</p>';
} else {
// Parse the cart session variable
$items = explode(',',$cart);
$s = (count($items) > 1) ? 's':'';
return '<p>You have '.count($items).' item'.$s.' in your shopping cart</p>';
}
}
function showCart() {
$currency = 'UGX';
global $db;
$cart = $_SESSION['cart'];
if ($cart) {
$items = explode(',',$cart);
$contents = array();
foreach ($items as $item) {
$contents[$item] = (isset($contents[$item])) ? $contents[$item] + 1 : 1;
}
$output[] = '<form action="cart.php?action=update" method="post" id="cart">';
$output[] = '<table class="table table-striped">';
foreach ($contents as $id=>$qty) {
$sql = 'SELECT * FROM products WHERE product_id = '.$id;
$result = $db->query($sql);
$row = $result->fetch();
extract($row);
$output[] = '<tr>';
$output[] = '<td>Remove</td>';
$output[] = '<td>'.$product_name.'</td>';
$output[] = '<td>'.$currency.''.$product_price.'</td>';
$output[] = '<td><input type="text" name="qty'.$id.'" value="'.$qty.'" size="3" maxlength="3" /></td>';
$output[] = '<td>'.$currency.''.($product_price * $qty).'</td>';
$total += $product_price * $qty;
$output[] = '</tr>';
}
$output[] = '</table>';
$output[] = '<p>Grand total: <strong>'.$currency.''.$total.'</strong></p>';
$output[] = '<div><button type="submit">Update cart</button></div>';
$output[] = '</form>';
} else {
$output[] = '<p>You shopping cart is empty.</p>';
}
return join('',$output);
}
?>
This is my cart script that handles actions from the cart buttons(add, delete and update)
<?php
session_start();
$cart = $_SESSION['cart'];
$action = $_GET['action'];
switch ($action) {
case 'add':
if ($cart) {
$cart .= ','.!isset($_GET['product_id']);
} else {
$cart = !isset($_GET['product_id']);
}
break;
case 'delete':
if ($cart) {
$items = explode(',',$cart);
$newcart = '';
foreach ($items as $item) {
if (!isset($_GET['product_id']) != $item) {
if ($newcart != '') {
$newcart .= ','.$item;
} else {
$newcart = $item;
}
}
}
$cart = $newcart;
}
break;
case 'update':
if ($cart) {
$newcart = '';
foreach ($_POST as $key=>$value) {
if (stristr($key,'qty')) {
$id = str_replace('qty','',$key);
$items = ($newcart != '') ? explode(',',$newcart) : explode(',',$cart);
$newcart = '';
foreach ($items as $item) {
if ($id != $item) {
if ($newcart != '') {
$newcart .= ','.$item;
} else {
$newcart = $item;
}
}
}
for ($i=1;$i<=$value;$i++) {
if ($newcart != '') {
$newcart .= ','.$id;
} else {
$newcart = $id;
}
}
}
}
}
$cart = $newcart;
break;
}
$_SESSION['cart'] = $cart;
?>
And this is how send actions to my cart from the add button
<form action="cart.php?action=add&id=<?php echo $row_prdt_details['product_id']; ?>" method="post" id="cart">
<fieldset>
<address>
<strong>Name:</strong> <span><?php echo $row_prdt_details['product_name']; ?></span><br>
<strong>Cake Code:</strong> <span><?php echo $row_prdt_details['product_id']; ?></span><br>
<strong>Availability:</strong> <span>
</span><br>
</address>
<h4><strong>Price: UGX <?php echo $row_prdt_details['product_price']; ?></strong></h4>
<p> </p>
<label>Qty:</label>
<input type="text" class="span1" name="qty" placeholder="1">
<input type="submit" onClick="window.location.reload()" />
</fieldset>
</form>
All i want to achieve is to be able to add more items
Any help is greatly welcomed, if u have any questions about what am doing please ask me
Related
<?php
try {
$stmt2 = $db->query("SELECT cid, parent, name FROM category");
$row_count = $stmt2->rowCount();
if ($row_count) {
$rows = $stmt2->fetchAll(PDO::FETCH_ASSOC);
}
} catch (PDOException $e) {
echo $e->getMessage();
}
$items = $rows;
$id = '';
echo "<select>";
foreach ($items as $item) {
if ($item['parent'] == 0) {
echo "<option><a href='#'>".$item['name']."</a>";
$id = $item['cid'];
sub($items, $id);
echo "</option>";
}
}
echo "</select>";
function sub($items, $id){
foreach ($items as $item) {
if ($item['parent'] == $id) {
$x = '-';
$x++;
echo "<option>".$x."<a href='#'>".$item['name']."</a>";
sub($items, $item['cid']);
echo "</option>";
}
}
}
?>
This is my dropdown menu code. I want this "-" character in each parent item and auto increment this character in each parent item.
Like this select menu:
I think you need to use str_repeat()
example:
foreach ($items as $item) {
if ($item['parent'] == 0) {
echo "<option><a href='#'>".$item['name']."</a>";
$id = $item['cid'];
sub($items, $id, 1);
echo "</option>";
}
}
echo "</select>";
function sub($items, $id, $counter){
foreach ($items as $item) {
if ($item['parent'] == $id) {
echo "<option>".str_repeat("-",$counter)."<a href='#'>".$item['name']."</a>";
sub($items, $item['cid'],$counter+1);
echo "</option>";
}
}
}
I want to update the quantity of an item in the cart
These are the actions:
if(!empty($_GET["action"])) {
switch($_GET["action"]) {
case "add":
if(!empty($_POST["quantity"])) {
$productByCode = $db_handle->runQuery("SELECT * FROM menu WHERE item_code='" . $_GET["code"] . "'");
$itemArray = array($productByCode[0]["item_code"]=>array('name'=>$productByCode[0]["item_name"], 'code'=>$productByCode[0]["item_code"], 'quantity'=>$_POST["quantity"], 'price'=>$productByCode[0]["item_price"]));
if(!empty($_SESSION["cart_item"])) {
if(in_array($productByCode[0]["item_code"],$_SESSION["cart_item"])) {
foreach($_SESSION["cart_item"] as $k => $v) {
if($productByCode[0]["item_code"] == $k)
$_SESSION["cart_item"][$k]["quantity"] = $_POST["quantity"];
}
} else {
$_SESSION["cart_item"] = array_merge($_SESSION["cart_item"],$itemArray);
}
} else {
$_SESSION["cart_item"] = $itemArray;
}
}
break;
case "remove":
if(!empty($_SESSION["cart_item"])) {
foreach($_SESSION["cart_item"] as $k => $v) {
if($_GET["code"] == $k)
unset($_SESSION["cart_item"][$k]);
if(empty($_SESSION["cart_item"]))
unset($_SESSION["cart_item"]);
}
}
break;
case "empty":
unset($_SESSION["cart_item"]);
break;
}
}
This is the cart code:
<?php
foreach ($_SESSION["cart_item"] as $item){
?>
<tr>
<td><strong><?php echo $item["name"]; ?></strong></td>
<td><?php echo $item["quantity"]; ?></td>
<td><?php echo "₹".$item["price"]; ?></td>
<td><a id="remove" href="index.php?action=remove&code=<?php echo $item["code"]; ?>"><span class="fa fa-times fa-lg" style="color:red;"></span></a></td>
</tr>
<?php
$item_total += ($item["price"]*$item["quantity"]);
}
?>
I need something like when click on update button so it can take the value and update the session array of particular product quantity
Please help me out...
This is a pretty basic example, but you should make a function per action so you can more easily port the cart. Also, I am not sure why you have a $_GET in the switch and a $_POST in the case():
function AddToCart($default = 1)
{
// Set a default quantity (1). Check that the value is set and is number
// Not sure why you are using a get for the code but not for these
// attributes. Should it not be $_GET['quantity']??
$qty = (isset($_POST['quantity']) && is_numeric($_POST['quantity']))? $_POST['quantity']:$default;
// Check that there is a valid numeric itemcode
$item = (isset($_POST['item_code']) && is_numeric($_POST['item_code']))? $_POST['item_code']:false;
// If false, stop
if(!$item)
return;
// Do your product query
$productByCode = $db_handle->runQuery("SELECT * FROM menu WHERE item_code='" . $_GET["code"] . "'");
// Assign the item code
$itmcd = $_GET["code"];
$itemArray['code'] = $itmcd;
$itemArray['name'] = $productByCode[0]["item_name"];
$itemArray['price'] = $productByCode[0]["item_price"];
$itemArray['quantity'] = (isset($_SESSION["cart_item"][$itmcd]))? $_SESSION["cart_item"][$itmcd]['quantity']+$qty : $qty;
$_SESSION["cart_item"][$itmcd] = $itemArray;
}
To use:
if(isset($_GET["action"]) && $_GET["action"] == 'add'))
AddToCart();
I have no idea where to get size value and input it to my database
this is my database table called transaksi with these column
idtransaksi, noinvoice, idproduk, size, jumlah
and here is my script
chart.php
<?php
if (!isset($_SESSION)) {
session_start();
}
cek_status_login($_SESSION['idpelanggan']);
include ('chart.inc.php');
// Process actions
$chart = isset ($_SESSION['chart']) ? $_SESSION['chart'] : '';
$action = isset($_GET['action']) ? $_GET['action'] : '';
switch ($action) {
case 'add' :
if ($chart) {
$chart .= ',' . $_GET['id'];
} else {
$chart = $_GET['id'];
}
break;
//
//B002,5,S,B003,10,M
case 'delete' :
if ($chart) {
$items = explode(',', $chart);
$newchart = '';
foreach ($items as $item) {
if ($_GET['id'] != $item) {
if ($newchart != '') {
$newchart .= ',' . $item;
} else {
$newchart = $item;
}
}
}
$chart = $newchart;
}
break;
case 'update' :
if ($chart) {
$newchart = '';
foreach ($_POST as $key => $value) {
if (stristr($key, 'qty')) {
$id = str_replace('qty', '', $key);
$items = ($newchart != '') ? explode(',', $newchart) : explode(',', $chart);
$newchart = '';
foreach ($items as $item) {
if ($id != $item) {
if ($newchart != '') {
$newchart .= ',' . $item;
} else {
$newchart = $item;
}
}
}
for ($i = 1; $i <= $value; $i++) {
if ($newchart != '') {
$newchart .= ',' . $id;
} else {
$newchart = $id;
}
}
}
}
}
$chart = $newchart;
break;
}
$_SESSION['chart'] = $chart;
?>
<section class="main-content">
<div class="row">
<div class="span9">
<?php echo writeShoppingchart();
echo showchart();
if (isset($_GET['s'])) {
if ($_GET['status'] == OK) {
echo "proses pembelian berhasil dilakukan sudah selesai";
} else {
echo "operasi gagal";
}
}
?>
</div>
<script type="text/javascript">
$('.input').on('input',function(e){
if($(this).data("lastval")!= $(this).val()){
$(this).data("lastval",$(this).val());
//change action
alert('Anda Mengubah Jumlah SubTotal barang, Silahkan Update Keranjang Belanja');
};
});
</script>
<?php
include ('inc/sidebar-front.php');
?>
</div>
</section>
chart.inc.php
<?php
function kd_transaksi() {
$kode_temp = fetch_row("SELECT noinvoice FROM invoice ORDER BY noinvoice DESC LIMIT 0,1");
if ($kode_temp == '')
$kode = "E00001";
else {
$jum = substr($kode_temp, 1, 6);
$jum++;
if ($jum <= 9)
$kode = "E0000" . $jum;
elseif ($jum <= 99)
$kode = "E000" . $jum;
elseif ($jum <= 999)
$kode = "E00" . $jum;
elseif ($jum <= 9999)
$kode = "E0" . $jum;
elseif ($jum <= 99999)
$kode = "E" . $jum;
else
die("Kode pemesanan melebihi batas");
}
return $kode;
}
function writeShoppingchart() {
$chart = $_SESSION['chart'];
if (!$chart) {
return '<h4 class="title"><span class="text pull-left"><strong>Keranjang Belanja Masih Kosong</strong></span></h4>';
} else {
// Parse the chart session variable
$items = explode(',', $chart);
$s = (count($items) > 1) ? 's' : '';
return '<h4 class="title"><span class="text pull-left"><strong>Periksa Jumlah Pesanan Anda Sebelum Check Out</strong></span></h4>';
}
}
function chartNotification() {
$chart = $_SESSION['chart'];
if (!$chart) {
return '0';
} else {
// Parse the chart session variable
$items = explode(',', $chart);
return count($items);
}
}
function getQty() {
$chart = $_SESSION['chart'];
if (!$chart) {
return 0;
} else {
// Parse the chart session variable
$items = explode(',', $chart);
$s = (count($items) > 1) ? 's' : '';
return count($items);
}
}
function showchart() {
$chart = $_SESSION['chart'];
// print_r($chart);
if ($chart) {
$items = explode(',', $chart);
$contents = array();
$total='';
foreach ($items as $item) {
$contents[$item] = (isset($contents[$item])) ? $contents[$item] + 1 : 1;
}
$output[] = "<table class=\"table table-striped \">";
$output[] = "<th><td>Nama</td><td>size</td><td> Harga</td><td>jumlah</td><td>diskon</td><td>subtotal</td><td>Aksi</td></th>";
$output[] = '<form action="index.php?mod=chart&pg=chart&action=update" method="post" id="chart">';
$no = 1;
foreach ($contents as $id => $qty) {
$sql = "SELECT produk.*, stok.harga_barang, stok.harga_jual, stok.jumlah, stok.ext_disc, stok.disc, stok.size FROM stok LEFT OUTER JOIN produk ON stok.idproduk = produk.idproduk WHERE produk.idproduk = '$id'";
$result = mysql_query($sql);
$row = mysql_fetch_object($result);
$size = explode(',', $row->size);
$quantity = ($row->jumlah);
$diskonext =(($row->harga_jual)*($row->ext_disc)/100);
$output[] = '<tr><td>' . $no . '</td>';
$output[] = '<td>'.$row ->nama_produk. '<br /><img src=\'upload/produk/' . $row ->foto .' \' width=\'100px\' height=\'100px\'></td>';
$output[] = '<td><select name="size" style="width:50px;">';
for ($i = 0; $i < count($size); $i++){
$output[] = '<option value="'. $size[$i] .'">'. $size[$i] .'</option>';
}
$output[] = '</select></td>';
$output[] = '<td>' . format_rupiah($row -> harga_barang) . '</td>';
if ($qty >= 10){
$total += (($row -> harga_jual) - $diskonext) * $qty;
}else {
$total += $row -> harga_jual * $qty;
}
if ($qty > $quantity){
$output[] = '<td><input type="text" class="input-mini" name="qty' . $id . '" value="'.$quantity.'"/><br /><span class="label label-warning pull-right">Stok hanya '.$quantity.'</span></td>';
} else {
$output[] = '<td><input type="text" onkeypress="alert(\'jumlah barang terganti, silahkan Update Keranjang belanja anda sebelum chekout\');" class="input-mini" name="qty' . $id . '" value="' . $qty . '"/></td>';
}
if ($qty >= 10){
$output[] = '<td>' . $row->disc . ' % + '. $row -> ext_disc .'% </td>';
} else {
$output[] = '<td>' . $row->disc . ' %</td>';
}
if ($qty >= 10){
if ($qty > $quantity){
$output[] = '<td>'.format_rupiah(($row->harga_jual - $diskonext)*$quantity).'</td>';
} else {
$output[] = '<td>'.format_rupiah(($row->harga_jual - $diskonext)*$qty).'</td>';
}
}else{
if ($qty >= $quantity){
$output[] = '<td>'.format_rupiah($row->harga_jual*$quantity).'</td>';
} else {
$output[] = '<td>'.format_rupiah($row->harga_jual*$qty).'</td>';
}
}
$output[] = '<td>Hapus</td></tr>';
$no++;
}
$output[] = '<tr><td colspan=\'6\' ><h4>Total Belanja Anda</h4></td><td colspan=\'2\'><h4>'. format_rupiah($total) .'</h4></td></tr>';
$output[] = "</table>";
$qty = getQty();
$_SESSION['totalbayar'] = $total;
$output[] = '<button type="submit" class=\'btn btn-primary\'>Update Keranjang Belanja</button>';
if ($qty >= ($row->jumlah)){
$output[] ='<button type="submit" class=\'btn btn-success pull-right\'>Update Keranjang Belanja Anda</button>';
} else {
$output[] ='<a href=\'chart/chart_action.php\' class=\'btn btn-success pull-right\'>Check out</a>';
}
$output[] = '</form>';
} else {
$output[] = '<p>Keranjang belanja masih kosong.</p>';
}
return join('', $output);
}
function insertToDB($kd_transaksi, $idpelanggan, $totalbayar, $sizes) {
$chart = isset($_SESSION['chart'])? $_SESSION['chart']: '';
if ($chart) {
$items = explode(',', $chart);
$contents = array();
foreach ($items as $item) {
$contents[$item] = (isset($contents[$item])) ? $contents[$item] + 1 : 1;
}
$sql_transaksi = "insert into invoice (noinvoice,tanggal,totalbayar,idpelanggan)
values( '$kd_transaksi', now(),'$totalbayar','$idpelanggan')";
//echo "SQL transaksi:".$sql_transaksi;
mysql_query($sql_transaksi) or die(mysql_error());
foreach ($contents as $id => $qty) {
$sql = "insert into transaksi(noinvoice,idproduk,size,jumlah)
values('$kd_transaksi','$id','$sizes','$qty')";
// echo "SQL transaksi:".$sql;
$result = mysql_query($sql) or die(mysql_error());
}
} else {
$output[] = '<p>Keranjang belanja masih kosong.</p>';
}
}
?>
and chart.action.php
<?php
session_start();
require_once ('../inc/config.php');
require_once ('../inc/function.php');
require_once ('../chart/chart.inc.php');
$idpelanggan=$_SESSION['idpelanggan'];
/* menambahkan kode pesan dan detail pesan kedalam database*/
$kd_transaksi = kd_transaksi();
$total_bayar = $_SESSION['totalbayar'];
insertToDB($kd_transaksi,$idpelanggan,$total_bayar);
//check if query successful
$link="location:../index.php?mod=chart&pg=chart_ship&total_bayar=$total_bayar&kd_transaksi=$kd_transaksi";
header($link);
?>
Still get confused how to input size value to database. and if you need more information to help me just tell me what I have to do
Thanks
The function insertToDB is defined with 4 parameters in the code above:
function insertToDB($kd_transaksi, $idpelanggan, $totalbayar, $sizes) {
But it is called with only 3 values:
insertToDB($kd_transaksi,$idpelanggan,$total_bayar);
So I suggest passing the value posted for variable size when calling the function:
insertToDB($kd_transaksi,$idpelanggan,$total_bayar,$_POST["size"]);
Btw: commenter #giraff is absolutely right when meaning the SQL injection. Your scripts are vulnerable to it. You should definitely check and sanitize user-submitted data!
I am trying to make nested categories in Laravel. I have created following models: Category.php, ItemsHelper.php (this one for displaying nested categories).
ItemsHelper.php:
class ItemsHelper {
private $items;
public function __construct($items) {
$this->items = $items;
}
public function htmlList() {
return $this->htmlFromArray($this->itemArray());
}
private function itemArray() {
$result = [];
foreach($this->items as $item) {
if ($item->parent_id == 0) {
$result[$item->title] = $this->itemWithChildren($item);
}
}
return $result;
}
private function childrenOf($item) {
$result = [];
foreach($this->items as $i) {
if ($i->parent_id == $item->id) {
$result[] = $i;
}
}
return $result;
}
private function itemWithChildren($item) {
$result = [];
$children = $this->childrenOf($item);
foreach ($children as $child) {
$result[$child->title] = $this->itemWithChildren($child);
}
return $result;
}
private function htmlFromArray($array) {
$html = '';
foreach($array as $k => $v) {
$html .= "<ul>";
$html .= "<li>" . $k . "</li>";
if(count($v) > 0) {
$html .= $this->htmlFromArray($v);
}
$html .= "</ul>";
}
return $html;
}
}
Then i am printing nested list of data in my index.blade.php:
{{ $itemsHelper->htmlList() }}
However this prints only plain titles and i need to convert them in to a links to my category, e.g. htmlFromArray() method:
$html .= "<li>" . $k . "</li>";
method itemArray():
$result[$item->title] = $this->itemWithChildren($item);
How can i add to this array id of each item?
You should probably change methods itemArray, itemWithChildren and htmlFromArray this way:
private function itemArray()
{
$result = [];
foreach ($this->items as $item) {
if ($item->parent_id == 0) {
$record['title'] = $item->title;
$record['id'] = $item->id;
$record['children'] = $this->itemWithChildren($item);
$result[] = $record;
}
}
return $result;
}
private function itemWithChildren($item)
{
$result = [];
$children = $this->childrenOf($item);
foreach ($children as $child) {
$record['title'] = $child->title;
$record['id'] = $child->id;
$record['children'] = $this->itemWithChildren($child);
$result[] = $record;
}
return $result;
}
private function htmlFromArray($array)
{
$html = '';
foreach ($array as $item) {
$html .= "<ul>";
$html
.=
'<li><a href="/category/' . $item['id'] . '">' . $item['title']
. "</a></li>";
if (count($item['children']) > 0) {
$html .= $this->htmlFromArray($item['children']);
}
$html .= "</ul>";
}
return $html;
}
Now you can store in your arrays id, title and list of element children so you can access iun htmlFromArray all those elements attributes.
When I add multiple products to the shopping cart, it duplicates the product data which was first inserted. The prepare statement in showCart() also echo's 'There's something wrong', while the data is still displayed, I suppose my code looks quite nasty. Excuses for that, I'm planning on cleaning it, when I get it to function
public function displayProduct()
{
if($product = $this->db->query("SELECT id, title, description, price FROM trips ORDER BY id"))
{
while ($row = $product->fetch_assoc())
{
$output[] = '<div class="reisbox">';
$output[] = '<div id="reis_insidebox1">';
$output[] = '<div class="reis_textbox">';
$output[] = '<h2>'.ucfirst($row['title']).'</h2>';
$output[] = '<article>';
$output[] = ucfirst($row['description']);
$output[] = '</article>';
$output[] = '</div>';
$output[] = '<div class="rightboxx">';
$output[] = '<div class="reis_price_box">';
$output[] = '<div class="reis_price_box_text">';
$output[] = '€'.$row['price'];
$output[] = '</div>';
$output[] = '<div class="more_box">';
$output[] = '<p>Lees meer..</p>';
$output[] = '</div>';
$output[] = '</div>';
$output[] = '</div>';
$output[]='<br />';
$output[] = '<div id="add">';
$output[]='Add to cart';
$output[] = '</div>';
$output[] = '<div class="review_box">';
$output[] = '<div class="review_text">Review</div>';
$output[] = '<div class="review_textbox"> Fantastische ontvangst met kleine attenties. Fantastisch ontbijt,. Goede bedden en ruime zitgelegenheid in de serre.</div>';
$output[] = '<div class="star_box"></div>';
$output[] = '<div class="review_linkbox">';
$output[] = 'Schrijf review';
$output[] = '</div>';
$output[] = '</div>';
$output[] = '</div>';
}
echo implode($output);
}
public function showCart() {
$cart = $_SESSION['cart'];
if ($cart) {
$items = explode(',',$cart);
$contents = array();
foreach ($items as $item) {
$contents[$item] = (isset($contents[$item])) ? $contents[$item] + 1 : 1;
}
$output[]='<div id="contents">';
$output[] = '<form action="index.php?page=cart.php&action=update" method="post" id="cart">';
$output[]='<table id="table_cart">';
$output[]='<thead>';
$output[]='<tr>';
$output[]='<th scope="col"></th>';
$output[]='<th scope="col">Informatie</th>';
$output[]='<th scope="col">Prijs</th>';
$output[]='<th scope="col">Aantal</th>';
$output[]='<th scope="col">Prijs Totaal</th>';
$output[]='</tr>';
$output[]='</thead>';
foreach ($contents as $id=>$qty)
{
$sql = 'SELECT id, title, description, price FROM trips WHERE id = ?';
if($result = $this->db->prepare($sql))
{
$result->bind_param('i', $id);
$result->execute();
$result->bind_result($id, $title, $description, $price);
$result->fetch();
}
else
{
echo "something went wrong";
}
$output[]='<tr>';
$output[]='<td><p>Remove</p></td>';
$output[]='<td>'.$title.'</td>';
$output[]='<td>€'.$price.'</td>';
$output[]='<td><input type="text" name="qty'.$id.'" value="'.$qty.'" size="3" maxlength="3" /></td>';
$output[]='<td>€'.($price * $qty).'</td>';
$total += $price * $qty;
$output[]='</tr>';
}
$output[] = '<div id="total">';
$output[] = '<p>Grand total: <strong>€'.$total.'</strong></p>';
$output[] = '<button type="submit">Update cart</button>';
$output[] = '</div">';
$output[] = '</table>';
$output[]='</form>';
$output[] = '</div">';
} else {
$output[] = '<p>You shopping cart is empty.</p>';
$output[] = '<p>terug naar reizen</p>';
}
return implode('',$output);
}
First off, this is two separate bugs, and unless there is something else going on you aren't telling us the first script has nothing to do with either.
Bug 1: If your script echos "something went wrong" during a call to showCart() then you should be debugging your database connection and your statement prepare. Unless some of those column names or the row name is wrong, the error will most likely be in your connection. Try echoing the DB error info to see what is going on.
Bug 2: duplicated product data when showing cart:
To properly debug this we'd need to see how you add a product to the cart in the first place, but likely however you do so is interacting with this line negatively:
foreach ($items as $item) {
$contents[$item] = (isset($contents[$item])) ? $contents[$item] + 1 : 1;
}
EDIT
Actually it probably isn't that line causing the second bug, it probably is the fact that you echo product info even if the DB call fails.