Im not pro in programming
i have a foreach loop that gets the values from a form calculating the total and subtotal
public function salecal()
{
if ($this->input->post())
{
$i = 0;
$data = array();
$subtotal = 0;
foreach($this->input->post('pname') as $d){
$data[] = array(
'pid' => $this->input->post('pid[]')[$i],
'pname' => $this->input->post('pname[]')[$i],
'quantity' => $this->input->post('qty[]')[$i],
);
foreach ($data as $entry) {
$qty = $entry['quantity'];
$pid = $entry['pid'];
$proname = $entry ['pname'];
}
$value = $this->insert_model->get_price($pid); ///pasing the product id to get the the price from database
foreach ($value->result() as $row)
{
$price = $row->price;
}
$total = $price * $qty; ////Total calculation
$subtotal = $subtotal + $total;/////Sub Total Calculation
$i++;
}
$result = compact("proname", "price", "qty", "total","i", "subtotal");
$this->load->view("bill", $result);
}
}
when i run this code im getting only the finally entered products details but the subtotal is correct
but the data inserting form is dynamic
what i want as result is
user will insert several or one item with quantity
data should be calculated and pass the calculated values to view
but currently im getting it only for the last inserted data please help me how to catch all the datas that user insert to form and how to pass them to view
Because your overwriting the variables consequently so it's passing last overwrite value only . you should make array for each one
This how you need to send all data to view using array
<?php
public function salecal()
{
if ($this->input->post())
{
$i = 0;
$data = array();
$subtotal = 0;
$final_array_collection =array();
foreach($this->input->post('pname') as $d){
$total =0; //reset the total to zero for each product
$pid = $this->input->post('pid[]')[$i];
$pname = $this->input->post('pname[]')[$i];
$quantity = $this->input->post('qty[]')[$i];
$value = $this->insert_model->get_price($pid); ///pasing the product id to get the the price from database
foreach ($value->result() as $row)
{
$price = $row->price;
}
$total = $price * $quantity; ////Total calculation
$subtotal = $subtotal + $total;/////Sub Total Calculation
$final_array_collection[] =array("proname"=>$pname, "price"=>$price, "qty"=>$quantity, "total"=>$total,"i"=>$i, "subtotal"=> $subtotal);
$i++;
}
$result = compact("final_array_collection");
$this->load->view("bill", $result);
}
}
?>
Related
I am using this on a shopping cart
if (!empty($_getvars['id'])) {
$data = $session->get('cart');
$data[] = $_getvars['id'];
$session->set('cart', $data);
}
$_getvars['id'] is productid, and on each click, a new array element will be added to the session. It works fine as it is now, but if a product is chosen more than once a new array will be added, how can change it that productid will be array offset and the value will be incremented from 1 each time to reflect the quantity?
$i = 1;
if (!empty($_getvars['id'])) {
$data = $session->get('cart');
$data[$_getvars['id']] = $i++;
$session->set('cart', $data);
}
but this code each time resets to 1. How to fix it? Or any better array structure for a shopping cart?
If it's not set, set it to zero, then always add one.
if (!empty($_getvars['id'])) {
$data = $session->get('cart');
if(!isset($data[$_getvars['id']]){
$data[$_getvars['id']] = 0;
}
$data[$_getvars['id']] += 1;
$session->set('cart', $data);
}
Or you could add a dynamic quantity
if (!empty($_getvars['id'])) {
$data = $session->get('cart');
if(!isset($data[$_getvars['id']]){
$data[$_getvars['id']] = 0;
}
// $_GET['qty'] OR 1, if not set
$qty = (!empty($_getvars['qty']))? $_getvars['qty']: 1;
$data[$_getvars['id']] += $qty;
$session->set('cart', $data);
}
I am trying to email the results held in an array ( shopping cart ) however when I send the email it is only the first name, price and qty which is displayed in the email and not any of the other names, prices or qty's. I am assuming there is something wrong with my loop but not sure where. Many thanks in advance. The results are placed in the comma_separated variable
$result= mysqli_query($conn, "SELECT * FROM testtable ");
// save product list as array
if (mysqli_num_rows($result) > 0) {
while($row = mysqli_fetch_object($result))
{
$sku = $row->ProductSKU;
$productInfo[$sku] = array();
$productInfo[$sku]['Name'] = $row->Name;
$productInfo[$sku]['Price'] = $row->Price;
$productInfo[$sku]['QTY'] = $row->QTY;
}
} else {
die ("ERROR");
}
$i=0;
$total=0;
// print the currently selected items
foreach ($_SESSION['cart'] as $sku => $quantity) {
$subtotal = $quantity * $productInfo[$sku]['Price'];
$total += $subtotal;
$array = array("Product:".$productInfo[$sku]['Name'],
"Units #".$productInfo[$sku]['Price'] ,
"Total:".number_format($subtotal, 2));
$comma_separated = implode("\n", $array);
}
You should probably change the following code:
// print the currently selected items
foreach ($_SESSION['cart'] as $sku => $quantity) {
$subtotal = $quantity * $productInfo[$sku]['Price'];
$total += $subtotal;
$array = array("Product:".$productInfo[$sku]['Name'],
"Units #".$productInfo[$sku]['Price'] ,
"Total:".number_format($subtotal, 2));
$comma_separated = implode("\n", $array);
}
into:
// print the currently selected items
$comma_separated = array();
foreach ($_SESSION['cart'] as $sku => $quantity) {
$subtotal = $quantity * $productInfo[$sku]['Price'];
$total += $subtotal;
$array = array("Product:".$productInfo[$sku]['Name'],
"Units #".$productInfo[$sku]['Price'] ,
"Total:".number_format($subtotal, 2));
$comma_separated[] = implode(', ',$array);
}
$comma_separated = implode("\n", $comma_separated);
Earlier you have created product array, imploded it using new line but finally you haven't saved this array in any other variable, so each time you run foreach loop you initialized $comma_separated variable again so the previous value wasn't there.
Now you should append $comma_separated to mail content, for example:
$mail_content .= $comma_separated;
I have a shopping cart, which works just fine, but I would like to store type of goods (for example color, size, etc.).
Here is a function that gets items from shopping cart
public static function getCart() {
if((isset($_SESSION['cart'])) && count($_SESSION['cart'])>0) {
$ids = "";
foreach($_SESSION['cart'] as $id => $quantity) {
$ids = $ids . $id . ",";
}
$ids = rtrim($ids, ',');
$dotaz = dibi::fetchAll("SELECT * FROM eshop_products WHERE idProduct IN ({$ids})");
return $dotaz;
} else {
//do nothing
}
}
And function that adds items to shopping cart
public static function addToCart($data) {
$id = $data['id'];
$quantity = $data['qty'];
$varianta = $data['varianty']; //THIS IS WHAT I NEED TO ADD TO SESSION ARRAY
if(!isset($_SESSION['cart'])) {
$_SESSION['cart'] = array();
}
if(isset($_SESSION['cart'][$id])) {
$_SESSION['cart'][$id] += $quantity;
} else {
$_SESSION['cart'][$id] = $quantity;
}
}
Is there some easy way to do that? I googled some tutorials, but still no success.
Thank you.
Maybe this is a hint for you:
$id = $data['id'];
$quantity = $data['qty'];
$varianta = $data['varianty']; //THIS IS WHAT I NEED TO ADD TO SESSION ARRAY
$cart = array();
array_push($cart, array(
'id' => $id,
'quantity' => $quantity,
'varianta' => $varianta
));
I need to calculate a sub total of the items in a shopping cart. It stores the items added to the cart as an array of the product IDs in a session variable.
So to start with I need to use the ID in the cart array to pull the product information from the database (name, price etc.) and then add the prices of all the items in the cart, of which there could be more than one of the same product.
My test cart should have a total price of 96,049.98 but my code is returning a total price of 18. I don't know where it's getting that from.
Here is the code:
function subTotal() {
global $db;
global $table_prefix;
$table = $table_prefix . "products";
foreach($_SESSION['cart'] as $item) {
$sql = $db->prepare("SELECT * FROM $table WHERE id = :id");
$sql->bindParam(":id", $item[0]);
$sql->execute();
$amount = 0;
$product = $sql->fetch(PDO::FETCH_ASSOC);
foreach($product as $price) {
$amount += $price['price'];
}
}
return $amount;
}
You are restarting the value $amount to 0 per iteration.
Try initializating it at the top:
function subTotal() {
global $db;
global $table_prefix;
$table = $table_prefix . "products";
$amount = 0; //MOVED HERE at the top
foreach($_SESSION['cart'] as $item) {
$sql = $db->prepare("SELECT * FROM $table WHERE id = :id");
$sql->bindParam(":id", $item[0]);
$sql->execute();
$product = $sql->fetch(PDO::FETCH_ASSOC);
foreach($product as $price) {
$amount += $price['price'];
}
}
return $amount;
}
Just take out $amount = 0 out of the loop. As it's getting reset on each product loop.
$amount = 0;
foreach($_SESSION['cart'] as $item) {
$sql = $db->prepare("SELECT * FROM $table WHERE id = :id");
$sql->bindParam(":id", $item[0]);
$sql->execute();
$product = $sql->fetch(PDO::FETCH_ASSOC);
foreach($product as $price) {
$amount += $price['price'];
}
}
As I mentioned in my comment: In case you are able to change the way your shopping cart stores items, you could refactor your code to something like this:
function subTotal() {
$db = $GLOBALS['db'];
$table_prefix = $GLOBALS['table_prefix'];
$table = $table_prefix . "products";
$totalPrice = 0;
// assuming that you actually store ($id => $amount) pairs
$ids = join(',', array_map('intval', array_keys($_SESSION['cart'])));
$stmt = $db->prepare("SELECT id, price FROM $table WHERE id IN ($ids)");
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
$amount = $_SESSION['cart'][$row['id']];
$totalPrice += $amount * $row['price'];
}
return $totalPrice;
}
If would assume, that your shopping cart variable would contain something like this:
array(
4 => 1, // 1 item with ID 4
22 => 8 // 8 items with ID 22
)
I need configure Product price range like
For the product name: $140 - 310 i use below code
if(Mage::getSingleton('customer/session')->isLoggedIn())
{
// Get group Id
$groupId = Mage::getSingleton('customer/session')->getCustomerGroupId();
}
else
{
$groupId = 0;
}
$db = Mage::getSingleton('core/resource')->getConnection('core_write');
$result = $db->query('SELECT price ,final_price, min_price, max_price, tier_price, group_price FROM catalog_product_index_price WHERE entity_id='.$_product->getId().' AND customer_group_id ='.$groupId.' ORDER BY customer_group_id ASC LIMIT 1');
$rows = $result->fetch();
i also need a regular price range for the configure product. i also think that my range after product name my be wrong because in Your Price have a price $135 so how can i get minimum value and maximum special price and also in regular price?
How can i get that?
Thanks and Regards
This answer to a similar question on the Magento StackExchange is a good basis to work from. Using that, here's a solution to this problem that takes into account the potential for configurable products having more than one price-changing attribute.
I've written it as function that takes a configurable product id, and returns a string of min to max price. It should be pretty clear how to work it into the context that you need.
function getPriceRange($productId) {
$max = '';
$min = '';
$pricesByAttributeValues = array();
$product = Mage::getModel('catalog/product')->load($productId);
$attributes = $product->getTypeInstance(true)->getConfigurableAttributes($product);
$basePrice = $product->getFinalPrice();
foreach ($attributes as $attribute){
$prices = $attribute->getPrices();
foreach ($prices as $price){
if ($price['is_percent']){ //if the price is specified in percents
$pricesByAttributeValues[$price['value_index']] = (float)$price['pricing_value'] * $basePrice / 100;
}
else { //if the price is absolute value
$pricesByAttributeValues[$price['value_index']] = (float)$price['pricing_value'];
}
}
}
$simple = $product->getTypeInstance()->getUsedProducts();
foreach ($simple as $sProduct){
$totalPrice = $basePrice;
foreach ($attributes as $attribute){
$value = $sProduct->getData($attribute->getProductAttribute()->getAttributeCode());
if (isset($pricesByAttributeValues[$value])){
$totalPrice += $pricesByAttributeValues[$value];
}
}
if(!$max || $totalPrice > $max)
$max = $totalPrice;
if(!$min || $totalPrice < $min)
$min = $totalPrice;
}
return "$min - $max";
}
can u try to get all the child products of that configurable product first, then get the price of each child product, and compare them, find the highest and the lowest.
//load configurable product
$product = Mage::getModel('catalog/product')->load(some_id);
//load all children
$childProducts = Mage::getModel('catalog/product_type_configurable')
->getUsedProducts(null,$product);
foreach($childProducts as $child){
$_child = Mage::getModel('catalog/product')->load($child->getId());
$childPrice = $_child->getPrice();
//compare the $childPrice
}
You can use something like this
$prices = array();
$associated = $_product->getTypeInstance(true)->getAssociatedProductCollection($_product)
->addAttributeToSelect('special_price');
foreach ($associated as $assoc) {
$prices[] = $assoc->getSpecialPrice();
}
// calculate min max price here
if (count($prices)) {
$min_price = min($prices);
$max_price = max($prices);
} else {
$min_price = 0;
$max_price = 0;
}
Maybe not perfect solution, but it works
Try using the $product->getMinPrice() and $product->getMaxPrice()
Take a look at app/code/core/Mage/Catalog/Model/Resource/Product/Collection.php