I'm making a shopping cart and I'm stuck on the actual cart. I've read a few questions on here and tried them but either they don't work for me, or they're plain rubbish.
PHP Code: addtocart.php
if(isset($_GET['product_id']) && isset($_GET['qty'])){
$product_id = $_GET['product_id'];
$qty = $_GET['qty'];
$cart = $_SESSION['cart'];
if($cart == null) {
$cart = array();
}
if(!isset($cart[$product_id])) {
$cart[$product_id] = 0;
}
$cart[$product_id] += $qty;
//var_dump($cart);
}
$session->setSetting("cart", $cart);
PHP Code: cart.php
try {
if(empty($_GET)) {
$cart = $session->getSetting("cart");
if($cart == null) {
throw new Exception("Empty cart.");
} else {
$template->setVar("cart", $cart);
} elseif($_GET['action'] == 'empty') {
unset($_SESSION['cart']);
header("location: /cart.php");
}
}
} catch (Exception $e) {
$template->setVar("errmsg", $e->getMessage());
}
Output:
<table class="table table-bordered table-striped table-condensed">
<?php foreach($this->cart as $product_id => $qty):
$item = $this->product->buildTotal($product_id); //var_dump($item);
?>
<tr>
<th>Items</th>
<td><?php echo count($item); ?>
</td>
<tr>
<th>Sub-total</th>
<td>
£<?php echo $price = number_format(($item[0]['product_price'] * $qty), 2); ?>
</td>
</tr>
<tr>
<th>Shipping</th>
<td>
£<?php echo $shipping = "2.95"; ?>
</td>
</tr>
<tr class="warning">
<th>Tax</th>
<td>20%</td>
</tr>
<tr class="success">
<th>Total</th>
<td>£<?php $tax = (($price * 20) / 100);
$total = ($price + $tax + $shipping);
echo number_format($total, 2); ?>
</td>
</tr>
<?php endforeach; ?>
Unfortunately, my error is that the totals table at the bottom of the cart displays 'x' amount of times for 'x' amount of products, example of two products makes the table display twice, rather than just totaling up the different prices etc. I've been stuck on this for three days so any help is greatly appreciated. Also, if your answer works, I'll list you in the credits page of the cart.
Related
I'm just trying to display the results in red or green depending on their value. Negative or Positive.
I have the following code but it is just not working. Can anyone please help?
<?php
$total = 0;
$index = 0;
foreach($products as $product){
$index ++;
?>
<tr>
<?php
$style = ($total < 0) ? "color:red; font-weight:bold;" : "color:green; font-weight:bold;";
?>
<td class="text-center" style="<?php echo $style ?>" >
<?php
$total_item = $product['quantity'] * $product['sale_price'];
$total += $total_item;
if ($index == count($products)) {
echo formatcurrency ($total);
}
?>
</td>
</tr>
<?php
}
?>
enter image description here
My original code was this here, but i only wanted the last value to be displayed so I modified to the code above. Now i need to display in RED if negative or Green if positive.
<table>
<?php
$total = 0;
foreach($products as $product){
?>
<tr>
<td>...</td>
<td>...</td>
<td>
<?php
$total_item = $product['quantity'] * $product['sale_price'];
$total += $total_item;
echo formatcurrency($total);
?>
</td>
</tr>
<?php
}
?>
... ... $-225.00
... ... $-755.00
... ... $-665.00
I am trying to create a shopping cart and take the quantities in the cart to subtract from my inventory in my table in mysql. But everytime i try and update it keeps on subtracting the wrong amount. So far i have this.
<form action="<?php $_SERVER['PHP_SELF'] ?>" method="POST">
<center><B>Invoice</B></center>
<?php
require 'connect.php';
require 'item.php';
if(isset($_GET['id'])){
$result = mysqli_query($con, 'select * from products where
id='.$_GET['id']);
$products = mysqli_fetch_object($result);
$item = new Item();
$item->id = $products->id;
$item->name = $products->name;
$item->price = $products->price;
$item->quantity = 1;
// Check if the products exists in the cart
$index = -1;
$cart = unserialize(serialize($_SESSION['cart']));
for($i=0; $i<count($cart); $i++)
if($cart[$i]->id==$_GET['id'])
{
$index = $i;
break;
}
if($index==-1)
$_SESSION['cart'][] = $item;
else{
$cart[$index]->quantity++;
$_SESSION['cart'] = $cart;
}
}
// Delete products in cart
if(isset($_GET['index'])){
$cart = unserialize(serialize($_SESSION['cart']));
unset($cart[$_GET['index']]);
$cart = array_values($cart);
$_SESSION['cart'] = $cart;
}
?>
<table cellpadding="3" cellspacing="3" border="0">
<tr>
<th>Id</th>
<th>Name</th>
<th>Price</th>
<th>Quantity</th>
<th>Sub-Total</th>
</tr>
<?php
$cart = unserialize(serialize($_SESSION['cart']));
$s = 0;
$index = 0;
for($i=0; $i<count($cart); $i++){
?>
<tr>
<td><?php echo $cart[$i]->id; ?></td>
<td><?php echo $cart[$i]->name; ?></td>
<td><?php echo $cart[$i]->price; ?></td>
<td><?php echo $cart[$i]->quantity; ?></td>
<td><?php echo $cart[$i]->price * $cart[$i]->quantity; ?></td>
</tr>
<?php
$index++;
$quantitycart=$cart[$i]->quantity;
$idcart=$cart[$i]->id;
}
?>
<td><input type="submit" name="submit" value="submit"></td></tr>
<tr><td colspan="5"</tr>
<tr>
</tr>
</table><br>
<?php
if(array_key_exists('submit', $_POST))
{ $results = mysqli_query($con, 'select * from products');
for($i=0; $i<count($cart); $i++)
{
while($products= mysqli_fetch_object($results)){
$quantity= $products->quantity;
$newquantity= $quantity-$quantitycart;
$sql = "UPDATE products SET quantity='$newquantity' WHERE id='$idcart'";
}}
if ($con->query($sql) === TRUE) {
echo "Record updated successfully";
} else {
echo "Error updating record: " . $con->error;
}
$con->close();
}
$con is my connnection. Any help would be appreciated. The main problem is located in the last part of the code.
I am working on a point of sale for a hardware shop developed using codeigniter framework.
I want to come up with a detailed statement of account like in the picture below
I have two tables which are sales and payment, I want to get data from this two tables so that I can generate a statement of account of a specific customer.
This will help since the customer can be able to see all the items he/she bought on cash basis or credit basis and also show how much they has paid grouped by date.
It will also be possible to calculate the amount due.
I can be able to list separately (sales and payment) by using the below code and thereby calculate the amount due.
Sales
<?php
$salestotal = 0;
if (is_array($sales) || is_object($sales))
{
foreach ($sales as $key=>$sale): {?>
<tr>
<td>
<?php echo $sale->date; ?>
</td>
<td>
<?php echo $sale->id; ?>
</td>
<td>
<?php echo $sale->grand_total; ?>
</td>
<td>
<?php echo $sale->paid; ?>
</td>
<td></td>
</tr>
<?php
if(isset($sale->grand_total))
$salestotal += $sale->grand_total;
} endforeach ; }?>
Payments
<?php
$paymentstotal = 0;
if (is_array($payments) || is_object($payments))
{
foreach ($payments as $key=>$payment): {?>
<tr>
<td>
<?php echo $payment->date; ?>
</td>
<td class="text-center">
<?php echo $payment->sale_id; ?>
</td>
<td class="text-center">
<?php echo $payment->paid_by; ?>
</td>
<td class="text-center">
<?php echo $payment->cheque_no; ?>
</td>
<td class="text-center">
<?php echo $payment->amount; ?>
</td>
<td class="text-center">
<?php echo $this->customers_model->getUserna($payment->created_by); ?>
</td>
<td class="text-center">
<?php echo $payment->pos_paid; ?>
</td>
<td class="text-center">
<?php echo $payment->pos_balance; ?>
</td>
<td class="text-right">
<?php echo $this->customers_model->getStorename($payment->store_id); ?>
</td>
</tr>
<?php
if(isset($payment->amount))
$paymentstotal += $payment->amount;
} endforeach ;}?>
My controller
function statement($id = NULL)
{
if (!$this->Admin) {
$this->session->set_flashdata('error', $this->lang->line('access_denied'));
redirect('pos');
}
if($this->input->get('id')) { $id = $this->input->get('id', TRUE); }
$this->data['sales'] = $this->customers_model->getSales($id);
$this->data['payments'] = $this->customers_model->getPayments($id);
$this->data['customer'] = $this->customers_model->getCustomername($id);
$this->data['customer_id'] = $id;
$this->page_cons('customers/statement', $this->data);
}
My Model
public function getSales($id)
{
$q = $this->db->get_where('sales', array('customer_id' => $id));
if( $q->num_rows() > 0 ) {
return $q->result();
}
return FALSE;
}
public function getPayments($id)
{
$q = $this->db->get_where('payments', array('customer_id' => $id));
if( $q->num_rows() > 0 ) {
return $q->result();
}
return FALSE;
}
How do I combine this two tables?
I hope I am clear enough on this question, I have been trying to Google but I have no luck.
I will appreciate any help. Thanks
Edit
MYSQL tables
Sales
Payments
You can reuse the given methods getSales() and getPayments() in a new method getSalesWithPayments() to combine the two results:
public function getSalesWithPayments($customerId) {
$sales = [];
foreach ($this->getSales($customerId) as $sale) {
$sale->payment = null;
$sales[$sale->id] = $sale;
}
foreach ($this->getPayments($customerId) as $payment) {
$sales[$payment->sale_id]->payment = $payment;
}
return $sales;
}
In the first loop you initialize $sale->payment (for the case that a sale has no payment yet) and populate the $sales array, which is indexed by the id column. This way you can easily access any sale by its id without an expensive search.
In the second loop you assign the payments to the corresponding sales.
Note that you might need to add logic to handle empty results (which wouldn't be necessary if you would just return an empty array instead of FALSE).
You can now use it like..
Controller:
$this->data['sales'] = $this->customers_model->getSalesWithPayments($id);
View:
<?php foreach ($sales as $sale): ?>
<tr>
<td><?php echo $sale->date; ?></td>
<td><?php echo $sale->id; ?></td>
...
<?php if($sale->payment !== null): ?>
<td><?php echo $sale->payment->date; ?></td>
<td><?php echo $sale->payment->amount; ?></td>
...
<?php else: // empty cells if no payment ?>
<td></td>
<td></td>
...
<?php endif; ?>
</tr>
<?php endforeach; ?>
If you post the sales and payments table the answer will be better and exact. You can use MySQL Join to get combined data from 2 tables.
Try this:
$this->db->select('*')
->from('sales')
->join('payments', 'payments.sales_id = sales.id', 'right')
->where(array('sales.customer_id' => $id));
$results = $this->db->get();
I'm having issues adding products to my shopping cart. In order to read it easier I'm only posing the php code. I'm not worried about security issues at this point, just looking to correct the issue with the product not showing up in the cart on the page view_cart.php . Can anyone see what I'm missing here? Also, the session is started on another page prior to them reaching this point.
<?php # add_cart.php
// This page adds beers to the shopping cart.
if (isset($_GET['beer_id'])) { // Check for a beer ID.
$beer_id = $_GET['beer_id'];
// Check if the cart already contains one of these beers;
// If so, increment the quantity:
if (isset($_SESSION['cart'][$beer_id])) {
echo '<p> same beer </p>';
$_SESSION['cart'][$beer_id]['quantity']++; // Add another.
// Display a message:
echo '<p> This brew was already in your cart so we added another to your shopping cart. </p>';
} else { // New product to the cart.
require ('mysqli_connect.php'); // Connect to the database.
$q = "SELECT price FROM beer WHERE beer_id='" . $beer_id . "'";
$r = mysqli_query ($dbc, $q);
if (mysqli_num_rows($r) == 1) { // Valid beer_ID.
// Fetch the information.
list($price) = mysqli_fetch_array ($r, MYSQLI_NUM);
// Add to the cart:
$_SESSION['cart'] = array('quantity' => 1, 'price' => $price);
echo $_SESSION['cart'][$beer_id][$r];
// Display a message:
echo '<p>' . $beer_id . 'has been added to your shopping cart.<br/>Go to Cart or Keep Shopping</p>';
} else { // Not a valid beer_ID.
echo '<div align="center">This page has been accessed in error!</div>';
}
mysqli_close($dbc);
}
}// End of isset conditional.
else { // No beer_ID.
echo '<div align="center">This page has been accessed in error!</div>';
}
?>
The page below is called from add_cart.php
<?php
# view_cart.php
// Check if the form has been submitted (to update the cart):
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
// Change any quantities:
foreach ($_POST['quantity'] as $k => $v) {
$beer_id = (int) $k;
$qty = (int) $v;
if ( $qty == 0 ) { // Delete.
unset ($_SESSION['cart'][$beer_id]);
} elseif ( $qty > 0 ) { // Change quantity.
$_SESSION['cart'][$beer_id]['quantity'] = $qty;
}
} // End of FOREACH.
} // End of SUBMITTED IF.
// Display the cart if it's not empty...
if (!empty($_SESSION['cart'])) {
// Retrieve information for beers in cart:
require ('mysqli_connect.php'); // Connect to the database.
$q = "SELECT beer_id, name, price FROM beer WHERE beer_id ='".$beer_id."'";
/*foreach ($_SESSION['cart'] as $beer_id => $value) {
$q .= $beer_id . ',';
}*/
$q = substr($q, 0, -1) . ') ORDER BY beer_id ASC';
$r = mysqli_query ($dbc, $q);
// Create a form and a table:
echo '<form action="view_cart.php" method="post">
<table border="0" width="90%" cellspacing="3" cellpadding="3" align="center">
<tr>
<td align="left" width="30%"><b>ID</b></td>
<td align="left" width="30%"><b>Name</b></td>
<td align="right" width="10%"><b>Price</b></td>
<td align="center" width="10%"><b>Qty</b></td>
<td align="right" width="10%"><b>Total Price</b></td>
</tr>
';
// Print each item...
$total = 0; // Total cost of the order.
while ($row = mysqli_fetch_array ($r, MYSQLI_ASSOC)) {
// Calculate the total and sub-totals.
$subtotal = $_SESSION['cart'][$row['beer_id']]['quantity'] * $_SESSION['cart'][$row['beer_id']]['price'];
$total += $subtotal;
// Print the row:
echo "\t<tr>
<td align=\"left\">{$row['name']}</td>
<td align=\"right\">\${$_SESSION['cart'][$row['beer_id']]['price']}</td>
<td align=\"center\"><input type=\"text\" size=\"3\" name=\"qty[{$row['beer_id']}]\" value=\"{$_SESSION['cart'][$row['beer_id']]['quantity']}\" /></td>
<td align=\"right\">$" . number_format ($subtotal, 2) . "</td>
</tr>\n";
} // End of the WHILE loop.
mysqli_close($dbc); // Close the db connection.
// Print the total, close the table, and the form:
echo '<tr>
<td colspan="4" align="right"><b>Total:</b></td>
<td align="right">$' . number_format ($total, 2) . '</td>
</tr>
</table>
<div align="center"><input type="submit" name="submit" value="Update My Cart" /></div>
</form><p align="center">Enter a quantity of 0 to remove an item.
<br /><br />Checkout</p>';
} else {
echo '<form action="view_cart.php" method="post">
<table border="0" width="90%" cellspacing="3" cellpadding="3" align="center">
<tr>
<td align="left" width="10%"><b>ID</b></td>
<td align="left" width="30%"><b>Name</b></td>
<td align="right" width="30%"><b>Price</b></td>
<td align="center" width="10%"><b>Qty</b></td>
<td align="right" width="10%"><b>Total Price</b></td>
</tr></table>
';
echo '<p>Your cart is currently empty.</p>';
}
?>
So i edited my own shop but im having some issues with it, for example it add 2 instead of 1 or it removes 2 instead of 1,
you can see how it looks on www.neobotmx.org/test/tienda.php <<< not opwn for the public yet >> thats why its on a test folder
The shop code :
<?php
$product_id = $_GET[id]; //the product id from the URL
$action = $_GET[action]; //the action from the URL
//if there is an product_id and that product_id doesn't exist display an error message
if($product_id && !productExists($product_id)) {
die("Error. Product Doesn't Exist");
}
switch($action) { //decide what to do
case "add":
$_SESSION['cart'][$product_id]++; //add one to the quantity of the product with id $product_id
break;
case "remove":
$_SESSION['cart'][$product_id]--; //remove one from the quantity of the product with id $product_id
if($_SESSION['cart'][$product_id] == 0) unset($_SESSION['cart'][$product_id]); //if the quantity is zero, remove it completely (using the 'unset' function) - otherwise is will show zero, then -1, -2 etc when the user keeps removing items.
break;
case "empty":
unset($_SESSION['cart']); //unset the whole cart, i.e. empty the cart.
break;
}
?>
<?php
if($_SESSION['cart']) { //if the cart isn't empty
//show the cart
echo "<table border=\"1\" align=\"center\" padding=\"3\" width=\"70%\">";
echo "<tr>";
//show this information in table cells
echo "<td align=\"center\"><strong>Producto</strong></td>";
//along with a 'remove' link next to the quantity - which links to this page, but with an action of remove, and the id of the current product
echo "<td align=\"center\"><strong>Cantidad</strong></td>";
echo "<td align=\"center\"><strong>Costo</strong></td>";
echo "</tr>";//format the cart using a HTML table
//iterate through the cart, the $product_id is the key and $quantity is the value
foreach($_SESSION['cart'] as $product_id => $quantity) {
//get the name, description and price from the database - this will depend on your database implementation.
//use sprintf to make sure that $product_id is inserted into the query as a number - to prevent SQL injection
$sql = sprintf("SELECT name, description, price FROM products WHERE id = %d;",
$product_id);
$result = mysql_query($sql);
//Only display the row if there is a product (though there should always be as we have already checked)
if(mysql_num_rows($result) > 0) {
list($name, $description, $price) = mysql_fetch_row($result);
$line_cost = $price * $quantity; //work out the line cost
$total = $total + $line_cost; //add to the total cost
echo "<tr>";
//show this information in table cells
echo "<td align=\"center\"><strong>$name</strong></td>";
//along with a 'remove' link next to the quantity - which links to this page, but with an action of remove, and the id of the current product
echo "<td align=\"center\"><strong>$quantity </strong>Borrar</td>";
echo "<td align=\"center\"><strong>$line_cost</strong></td>";
echo "</tr>";
}
}
//show the total
echo "<tr>";
echo "<td colspan=\"2\" align=\"right\"><strong>Total</strong></td>";
echo "<td align=\"right\"><strong>$total</strong></td>";
echo "</tr>";
echo "</table>";
}else{
//otherwise tell the user they have no items in their cart
echo "No tiene articulos en compra.";
}
//function to check if a product exists
function productExists($product_id) {
//use sprintf to make sure that $product_id is inserted into the query as a number - to prevent SQL injection
$sql = sprintf("SELECT * FROM products WHERE id = %d;",
$product_id);
return mysql_num_rows(mysql_query($sql)) > 0;
}
?>
</p>
<p><strong>Seguir Comprando</strong></p>
<?php
and now the display of the books / items / whatever you want.
<?php
define('MAX_REC_PER_PAGE', 1);
$sql = "SELECT id, name, description, price FROM products;";
$rs = mysql_query("SELECT COUNT(*) FROM products") or die("Imposible Realizar Operacion");
list($total) = mysql_fetch_row($rs);
$total_pages = ceil($total / MAX_REC_PER_PAGE);
$page = intval(#$_GET["page"]);
if (0 == $page){
$page = 1;
}
$start = MAX_REC_PER_PAGE * ($page - 1);
$max = MAX_REC_PER_PAGE;
$rs = mysql_query("SELECT id, name, description, price FROM products ORDER BY id
ASC LIMIT $start, $max") or die("Imposible Realizar Operacion");
?>
<table width="100%" height="404" border="0" cellpadding="12">
<?php
while (list($id, $name, $description, $price) = mysql_fetch_row($rs)) {
?>
<tr>
<td height="46" align="left" valign="middle"><p><strong> Producto :
<?= htmlspecialchars($name) ?>
</strong>
</p></td>
</tr>
<tr>
<td height="172" align="left" valign="middle"><p><strong>Descripcion :</strong></p>
<p>
<strong>
<?= htmlspecialchars($description) ?>
</strong></p></td>
</tr>
<tr>
<td height="67" align="left" valign="middle"><p><strong>Precio :
<?= htmlspecialchars($price) ?> </strong>
</p></td>
</tr>
<tr>
<td height="109" align="center" valign="middle"><strong><? echo "Comprar" ?> </strong></td>
</tr>
<?php
}
?>
</table>
<table border="0" cellpadding="5" align="center">
<tr>
<td><strong>Pagina : </strong></td>
<?php
for ($i = 1; $i <= $total_pages; $i++) {
$txt = $i;
if ($page != $i)
$txt = "$txt";
?>
<td align="center"><?= $txt ?></td>
<?php
}
?>
</table>
I have no idea where's the error on it...
Ty for the help :)
Obiusly you have to :
<?php session_start();?>
include your database
etc
You have in the style:
body {
background-image: url();
}
which is causing the browser to request the page again, which adds it to the cart again.
Instead of rendering the cart page, Once the code has modified the cart it should send a redirect to the cart page.