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.
Related
What I want if the result is not found from the query select, I want to show else function like:
else {
$html .= 'You have not added stock at all';
}
Because in this case I used string of html, I don't know how to echo the else statement.
More or less my codes is looking like this right now (There are many parts I have removed since it's too long)
<?php
include("../actions/config.php");
$resultsClaim = $mysqli->query("SELECT");
$orders = array();
$html = '';
if ($resultsClaim) {
while($obj = $resultsClaim->fetch_object()) {
$orders[$obj->id_cart][$obj->items] = array('status' => $obj->status ...);
}
foreach ($orders AS $order_id => $order) {
$orderCount = count($order);
$html .= '<tbody><tr><td rowspan="' . count($order) . '">' . $order_id . '</td>';
$row = 1;
foreach ($order AS $item => $data) {
if ($row > 1) { $html .= '</tr><tr>'; }
$html .= '<td>' . $item . '</td>';
$row++;
}
$html .= '<div>
<div class="member-popUpeStock'.$data['id'].' member-PopUp">
<div class="member-PopUp-box">
X
<div class="tablePopUp">
<div class="table-row">
<div class="col">: '.$data['method'].' </div>';
///HERE WHERE I WANT TO DO THAT////
else {
echo 'Nothing';
}
echo $html;
?>
Can anyone help me, please! Thanks in Advance.
Since you are taking the no of orders into a variable, you can make use of that directly to see if the orders exists or not.
$orderCount = 0; //Define orderCount in the beginning.
//Rest of the code, till foreach
foreach(){
//Rest of the code here
}
if(intval($orderCount) <= 0) //Using intval, for the case the for loop is not executed at all
{
$html = "Nothing";
}
Here you dont need to concatenate it to $html since you are displaying the table content if order exists or else you displaying "Nothing".
So $html will either have the table content or else "Nothing".
Hope this helps.
First get count of $orders
if (! empty($orders)) {
foreach ($orders AS $order_id => $order) {
// YOUR CODE HERE
}
}
else {
$html .= 'Nothing'; // Append your `no records found` message to the `$html` variable:
}
foreach ($orders AS $order_id => $order) { } else {}
So "}" is missing for foreach loop. Hope it will work for you. Let me know if you need further help.
Give it a try
<?php
include("../actions/config.php");
$resultsClaim = $mysqli->query("SELECT");
$orders = array();
$html = '';
if (!empty($resultsClaim)) {
while ($obj = $resultsClaim->fetch_object()) {
$orders [$obj->id_cart][$obj->items] = array('status' => $obj->status);
}
foreach ($orders AS $order_id => $order) {
$orderCount = count($order);
$html .= '<tbody><tr><td rowspan="' . count($order) . '">' . $order_id . '</td>';
$row = 1;
foreach ($order AS $item => $data) {
if ($row > 1) {
$html .= '</tr><tr>';
}
$html .= '<td>' . $item . '</td>';
$row++;
}
$html .= '<div>
<div class="member-popUpeStock' . $data['id'] . ' member-PopUp">
<div class="member-PopUp-box">
X
<div class="tablePopUp">
<div class="table-row">
<div class="col">: ' . $data['method'] . ' </div>';
}
}
///HERE WHERE I WANT TO DO THAT////
else {
echo 'Nothing';
}
echo $html;
?>
The variables are being posted from a previous page through array values.
when I print_r($values) I get the whole value on this array including the numerical values of the array ex: array[0], array[1] ..etc.
Please can some tell me what I am doing wrong. the implode function was not used because the values are passed from a cart page though session variables.
First part of code below:
<?php
$current_url = base64_encode($url="http://".$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI']);
if(isset($_SESSION["products"]))
{
$total = 0;
echo '<form method="post" action="process.php">';
echo '<ul>';
$cart_items = 0;
foreach ($_SESSION["products"] as $cart_itm)
{
$product_code = $cart_itm["code"];
$results = $mysqli->query("SELECT Title,Description,Price FROM main_menu WHERE MenuID='$product_code' LIMIT 1");
$obj = $results->fetch_object();
echo '<li class="cart-itm">';
echo '<span class="remove-itm">×</span>';
echo '<div class="p-price">'.$currency.$obj->Price.'</div>';
echo '<div class="product-info">';
echo '<h3>'.$obj->Title.' (Code :'.$product_code.')</h3> ';
echo '<div class="p-qty">Qty : '.$cart_itm["qty"].'</div>';
echo '<div>'.$obj->Description.'</div>';
echo '</div>';
echo '</li>';
$subtotal = ($cart_itm["price"]*$cart_itm["qty"]);
$total = ($total + $subtotal);
echo '<input type="hidden" name="item_name['.$cart_items.']" value="'.$obj->Title.'" />';
echo '<input type="hidden" name="item_code['.$cart_items.']" value="'.$product_code.'" />';
echo '<input type="hidden" name="item_desc['.$cart_items.']" value="'.$obj->Description.'" />';
echo '<input type="hidden" name="item_qty['.$cart_items.']" value="'.$cart_itm["qty"].'" />';
$cart_items ++;
}
echo '</ul>';
echo '<span class="check-out-txt">';
echo '<strong>Total : '.$currency.$total.'</strong> ';
echo '<input name=\'submit\' type="submit" value="Complete Order" style=\"width:150px;background:#333;color:#ffcc33;height:30px;\" />';
echo '</span>';
echo '</form>';
}else{
echo 'No items added';
}
?>
Second part:
Try $post and the table name in the given function and use mysql_real_escape_string() to avoid any possibility of the SQL Injection
form.php
<?php
include ('func_curd.php') ;
if($_POST['hiddenfieldinfo']=='ok')
{
$r=insert_your_table_name($_POST);
if($r==true)
{
header('Location:'.get_full_url()); /* to redirect the form to the same page after successful submission*/
}
}
?>
func_curd.php
<?php
function insert_your_table_name($post)
{
unset($post['hiddenfieldinfo']);
/* Here I am unsetting this value as it is hidden field
in the form , which I am using as form submission check and
is not in database column, apart form auto-increment in database
that is id, you have to maek sure all the post value and column
name matches with case-sensitivities */
$u = insert('your_table_name', $post);
$r=is_numeric($u)? true : false ;
return $r;
}
function insert($table, $values){
$query="INSERT INTO `$table` ";
$column='(';
$val=' (';
$count=count($values);
$mk=1;
foreach ($values as $key=>$value)
{
$value=mysql_real_escape_string($value);
if ($mk==$count)
{
$column .= '`'.$key.'`';
$val .= "'".$value."'";
}
else
{
$column .= '`'.$key.'`, ';
$val .= "'".$value."', ";
}
$mk++;
}
$column .=') ';
$val .=')';
$query=$query.$column.'VALUES'.$val;
$Q=mysql_query($query);
if(mysql_error())
{
return print(mysql_error());
}
else
{
$insert_id=mysql_insert_id();
return $insert_id;
}
}
?>
try this one:
<?php
require_once('config/connect.php');
$item_name = strip_tags($_POST['item_name']);
$item_code = strip_tags($_POST['item_code']);
$item_desc = strip_tags($_POST['item_desc']);
$item_qty = strip_tags($_POST['qty']);
$price = strip_tags($_POST['price']);
$fields = "item_name, item_code, item_desc, price,qty";
$query = "INSERT INTO `x` SET ";
$i = 0;
foreach( $fields as $fieldname )
{
if ( $i > 0 )
$query .= ", ";
$val = strip_tags($_POST[$fieldname]);
$query .= "`" . $fieldname . "` = '" . $val . "'"
$i++
}
$query_result = mysql_query($query);
echo" Record saved";
print_r ( $query );
?>
There are certain syntax errors in your code like not closed foreach etc. whihc I did skip.
As a recommendation: code like this is disclosing the database structure to everyone on the internet - form field names = database col names. This is generally a bad idea.
Better is a kind of mapping table:
$fields = array (
'myFormName' => 'mySqlName',
....
foreach( $fields as $fieldname => $sqlame)
{
if ( $i > 0 )
$query .= ", ";
$val = strip_tags($_POST[$fieldname]);
$query .= "`" . $sqlname. "` = '" . $val . "'"
....
which also will make the form more independent from the underlying data structures.
i have small page with cart. All things is storage in session. Now i need to save this data to mysql databse.
I think, that i need use foreach cycle to do this, but i cant construct it. Does anybody know the solution?
This is the function that displays cart.
function showCart() {
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">';
$total=0;
$output[] = '<table>';
foreach ($contents as $id_menu=>$qty) {
$sql = 'SELECT * FROM menu WHERE id_menu = '.$id_menu;
$result = $db->query($sql);
$row = $result->fetch();
extract($row);
$output[] = '<tr>';
$output[] = '<td>Delete</td>';
$output[] = '<td>' .$name. '</td>';
$output[] = '<td>' .$price.' Kč</td>';
$output[] = '<td><input type="text" name="qty'.$id_menu.'" value="'.$qty.'" size="5" maxlength="5" /></td>';
$output[] = '<td>' .($price * $qty).' Kč</td>';
$total += $price * $qty;
$output[] = '</tr>';
}
$output[] = '</table>';
$output[] = '<p>Total: <strong>'.$total.' EUR</strong></p>';
$output[] = '<div><button type="submit">Update</button></div>';
$output[] = '</form>';
} else {
$output[] = '<p>Cart is empty.</p>';
}
return join('',$output);
}
i think you need something like this....
foreach ($contents as $id_menu=>$qty)
{
$sql1 = 'INSERT INTO tablename (colum1, colum2, column3, ... ) SELECT * FROM menu WHERE id_menu = '.$id_menu;
//rest of your program
}
You can use:
Insert into mytable SELECT * FROM menu WHERE id_menu = ...
To construct the multiple insert and insert all in one statement, do the following:
Insert into mytable (col1, col2, col3) values
('Val1a','val2a','val3a'),
('Val1b','val2b','val3b'),
('Val1f','val2d','val3c'),
Etc...
;
Each iteration will concatenate one line of values. Insert is then done after the loop.
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
As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 9 years ago.
I have this shopping cart script that is run in a loop, but when i try to email it i only allows me to email 9 items anything more than 9 items the email just comes in blank. I was told that i should change my query 'SELECT * FROM books WHERE id = '.$id; to one that will return all items without the loop. Is this correct and what i should try to do? if so could someone give me a example of how i would do that?
<?php
function showCarts() {
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[] = '<table style="border-width:1px; bordercolor="#0099FF"">';
$output[] = '<tr>';
$output[] = '<thead bgcolor="#0099FF">';
$output[] = '<th>Item</th>';
$output[] = '<th>Price</th>';
$output[] = '<th>Quantity</th>';
$output[] = '<th>Total</th>';
$output[] = '</thead>';
$output[] = '</tr>';
foreach ($contents as $id=>$qty) {
$sql = 'SELECT * FROM books WHERE id = '.$id;
$result = $db->query($sql);
$row = $result->fetch();
extract($row);
$output[] = '<tr>';
$output[] = '<td>'.$title.' by '.$author.'</td>';
$output[] = '<td>$'.$price.'</td>';
$output[] = '<td>'.$qty.'</td>';
$output[] = '<td>$'.($price * $qty).'</td>';
$total += ($price * $qty);
$output[] = '</tr>';
}
$output[] = '</table>';
$tax = (.07);
$taxtotal += round($total * $tax,2);
$amounttotal += ($total + $taxtotal);
$output[] = '<p>Tax: <strong>$'.$taxtotal.'</strong></p>';
$output[] = '<p>Total: <strong>$'.$amounttotal.'</strong></p>';
}
return join('',$output);
}
?>
Replace your for-loop part with :
$ids = implode(',', array_keys($contents));
$sql = 'SELECT * FROM books WHERE id IN ('. $ids . ')';
$result = $db->query($sql);
while($row = $result->fetch()) {
extract($row);
$qty = $contents[(int)$row['id']]; // assuming your `$row` is an associative array of result
$output[] = '<tr>';
$output[] = '<td>'.$title.' by '.$author.'</td>';
$output[] = '<td>$'.$price.'</td>';
$output[] = '<td>'.$qty.'</td>';
$output[] = '<td>$'.($price * $qty).'</td>';
$total += ($price * $qty);
$output[] = '</tr>';
}