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;
Related
I am working on a project and I want to display Order Item Quantity with Order Item Products.
Here is my function
<?php
function wpallexport_order_items($value) {
$order = wc_get_order($value);
foreach ( $order->get_items() as $item ) {
$qty[] = $item->get_quantity();
$name[] = $item->get_name();
$q = implode($qty);
$n = implode($name);
$output = $q .' * '. $n .'<br>';
}
return $output;
}
?>
But it gives output format is
158 * Macroni Pasta Honey
And I want Output like
1 * Macroni
5 * Pasta
8 * Honey
How to get the required output ?
Regards
$data = [];
foreach ( $order->get_items() as $item ) {
// Collect all strings to one array
$data[] = $item->get_quantity() .' * '. $item->get_name();
}
// Then implode this array with `<br>` as glue
$output = implode('<br>', $data);
return $output;
$cats_array = array(1,7,28);
foreach ($cats_array as $category) {
$category_field_query = "SELECT fields
FROM categories
WHERE status = 1 AND id = $category";
$category_field_query_run = mysqli_query($connect, $category_field_query);
$cat_field = mysqli_fetch_object($category_field_query_run);
$field = explode(",", $cat_field->fields); /* Explode ',' from '/'3'/,' */
$field = str_replace("/","",$field); /* Delete all '/' */
print_r($field);
}
Inside foreach loop, my query returns something like that /7/,/13/,/24/ from fields for every turn, then I clean them from slashes and commas.
My goal is collect all that arrays inside one array.
I tried to create an empty array outside of foreach and sum all in it but it returned empty.
You have to be define $filed as a array before foreach loop. now you can store value into $filed. note that you have to multidimensional array required to store value.
$cats_array = array(1,7,28);
$field = array();
foreach ($cats_array as $category) {
$category_field_query = "SELECT fields FROM categories WHERE status = 1 AND id = $category";
$category_field_query_run = mysqli_query($connect, $category_field_query);
$cat_field = mysqli_fetch_object($category_field_query_run);
$field1 = explode(",", $cat_field->fields); /* Explode ',' from '/'3'/,' */
$field[] = str_replace("/","",$field1); /* Delete all '/' */
}
print_r($field);
I don't understand why do you store the fields like that, but here is a possible solution:
$fields = array();
$cats_array = array(1,7,28);
foreach ($cats_array as $category) {
$category_field_query = "SELECT fields FROM categories WHERE status = 1 AND id = $category";
$category_field_query_run = mysqli_query($connect, $category_field_query);
$cat_field = mysqli_fetch_object($category_field_query_run);
preg_match_all('/\/(\d+)\//', $cat_field->fields, $matches);
if (!empty($matches[1])) {
$fields = array_merge($fields, $matches[1]);
}
}
print_r($fields);
$fields = array();
$cats_array = array(1,7,28);
foreach ($cats_array as $category) {
$category_field_query = "SELECT fields FROM categories WHERE status = 1 AND id= $category";
$category_field_query_run = mysqli_query($connect, $category_field_query);
$cat_field = mysqli_fetch_object($category_field_query_run);
$field = explode(",", $cat_field->fields); // Explode ',' from '/'3'/,'
$field = str_replace("/", "", $field);
$fields[] = $field;
}
print_r($fields);
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);
}
}
?>
I have a CSV file with a header row. The code puts the column names as the $Key and $postion is the values. This works okay.
This is the loop creating the string of attributes to add to the product. When i "echo $sets" it displays correctly
foreach ($each_csv as $position => $details) {
$sets .= ->set$position('$details')}
$sets is creating the ->set code for the product. How do I implement the loop values into the product set function
$product->setWebsiteIds(array(1))
->setTypeId('simple')
->setMediaGallery (array('images'=>array (), 'values'=>array ()))
// How can I add the looped values here from the array
. Full Code Below
<?php
include ("../config/init.php");
Mage::app()->setCurrentStore(Mage_Core_Model_App::ADMIN_STORE_ID);
$product = Mage::getModel('catalog/product');
$rows = array_map('str_getcsv', file('prouduct_ids.csv'));
$header = array_shift($rows);
$csv = array();
foreach ($rows as $row) {
$csv[] = array_combine($header, $row);
}
//print_r($csv);
reset($csv);
$dataSetCount = count($csv);
echo "<h1>There are $dataSetCount products</h1>";
$i = 0;
foreach ($csv as $each_csv) {
$i++;
echo "<h2>csv $i</h2>";
if(!$product->getIdBySku($each_csv['Sku'])){
echo $each_csv['Sku'] . " - Already in website";
} else {
foreach ($each_csv as $position => $details) {
$sets .=->set$position('$details')}
$product->setWebsiteIds(array(1)) //website ID the product is assigned to, as an array
->setTypeId('simple') //product type
->setMediaGallery (array('images'=>array (), 'values'=>array ()));
//media gallery initialization
$product->save();
unset($sets);
}
}
You want to use the $product->setData('data_key', 'value') function.
For example, this function:
$product->setTypeId('simple')
Is the exact same as this function:
$product->setData('type_id', 'simple')
Keep in mind that a capital letter represents an underscore in the attribute name. typeId is type_id because the I in Id is capitalized.
The code in your functon will look like this:
[...]
foreach ($each_csv as $position => $details) {
$sets .= $product->setData($position, $details)
[...]
Where $position is the attribute code, and $details is the attribute value.
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
)