Add multiple products to cart - php

I have some problem with the logic and any help would be appreciated:
$total_add = $_POST['xTotalNumProduct'];
if(ISSET($_SESSION['cart']['CartTotalNum']) && $_SESSION['cart']['CartTotalNum'] > 0) {
$CartTotalNum = $_SESSION['cart']['CartTotalNum'];
$cart = $_SESSION['cart'];
for ($i=1; $i<=$total_add; $i++) {
for ($x=1; $x<=$CartTotalNum; $x++) {
if ($cart['ItemId'.$x] == $_POST['xPdt'.$i.'Id']) { // this will only check the first key ie $cart['ItemId1]
$cart['ItemQty'.$x] = $_POST['xPdt'.$i.'Qty'];
}
else {
$CartTotalNum = $CartTotalNum + 1;
$cart['ItemId'.$CartTotalNum] = $_POST['xPdt'.$i.'Id'];
$cart['ItemQty'.$CartTotalNum] = $_POST['xPdt'.$i.'Qty'];
}
}
}
$cart['CartTotalNum'] = $CartTotalNum;
} else {
$cart = array();
for ($i=1; $i<=$total_add; $i++) {
$cart['ItemId'.$i] = $_POST['xPdt'.$i.'Id'];
$cart['ItemQty'.$i] = $_POST['xPdt'.$i.'Qty'];
}
$cart['CartTotalNum'] = $total_add;
}
The problem with the above script is that it only checks the $cart['ItemId1] and if not equal it will add to cart without checking $cart['ItemId2], $cart['ItemId3] etc.
How can I fix that?

This is incredibly bad code:
$cart['ItemQty'.$x] = $_POST['xPdt'.$i.'Qty'];
^^^^^
Why build dynamic keys? You can use a multi-dimensional arrays quiet easily:
$_SESSION['cart'][$itemID]['quantity'] = $_POST[...];
Keying your cart by the itemID allows all of the item's cart data to be kept in one place, instead of scattered everywhere.
And note that similar constructs can be used in your form field names, e.g.
<input type="text" name="foo[bar][baz][42]" ... >
would give you
$_REQUEST['foo']['bar']['baz'][42]
to work with when the form's submitted.

This question was asked years ago, but for anyone running into it now, this is what worked for me.
I put this HTML in my page:
<form method="post" action="/">
<input type="hidden" name="E24MT1260" value="23">
<input type="hidden" name="ACFIT60060015" value="14">
<input type="hidden" name="programatic_add_to_cart" value="true">
<input type="submit" value="Add to cart">
</form>
And added this to my functions.php
<?php
add_action('wp_loaded', function() {
global $woocommerce;
if (!empty($_POST) && !empty($_POST['programatic_add_to_cart'])){
global $woocommerce;
foreach ($_POST as $sku => $quantity) {
$product_id = wc_get_product_id_by_sku($sku);
$woocommerce->cart->add_to_cart($product_id, $quantity);
}
wp_redirect( '/cart' );
exit;
}
});
?>

Related

How can I "link" two objects (like a keyword and its synonyms) in a php function?

I'm creating a form using php, html, css, and javascript.
On this form, the person needs to choose a few keywords and its synonyms.
It looks like this:
<form action="create.php" class="col-md-10 offset-md-1" method="post">
<div class="form-group" id="duplicateKeyWordAndSynonym">
<label for="keyWord">Type a keyword.</label>
<textarea class="form-control" id="terms" name="terms[]"></textarea> <br/>
<label for="synonym">Type the synonyms of your keyword.</label>
<textarea class="form-control" id="synonym" name="synonym[]"></textarea> <br/>
</div>
<button class="glass-button" type="button" id="add">click here to add more keywords and
synonyms.</button>
</form>
<script>
//https://api.jquery.com/click/
$("#add").click(function () {
//https://api.jquery.com/append/
$("#duplicateKeyWordAndSynonym").append('here is the code to duplicate the keywords and
synonyms part.');
});
</script>
Now, I have to connect my keywords to my synonyms on "create.php" so I can send this to the back-end.
I have tried a few things, but nothing seems to work.
This was my first try:
for ($i = 0; $i < count($terms); $i++) {
echo "TERM".$terms[$i];
echo "\nSynonym ".$synonym[$i];
$list[$terms[$i]] = $synonym[$i];
}
Last thing I tried was this:
for ($i = 0; $i < count($terms); $i++) {
echo "TERM".$terms[$i];
echo "\nSYNONYMS ".$synonims[$i];
$list->add("keyword" => $terms[$i],
"synonym" => $synonims[$i]);
}
It didn't work. What should I do?
======================================
Edit: Thanks for your comments, guys! This is how I solved the problem:
class Keyword{
public $keyword;
public $synonyms;
public function setKeyword($keyword){
$this->keyword = $keyword;
}
public function getKeyword(){
return $this->keyword;
}
public function setSynonyms($synonyms){
$this->synonyms = $synonyms;
}
public function getSynonyms(){
return $this->synonyms;
}
}
$terms = $_POST['terms'];
$synonym = $_POST['synonym'];
$arrayKeywords = array();
for ($i = 0; $i < count($terms); $i++) {
$keyword = new Keyword();
$keyword->setKeyword($terms[$i]);
$keyword->setSynonyms($synonym[$i]);
$arrayKeywords[] = $keyword;
}
You can submit the form in two ways:
1- in javascript, by putting in the script ( document.getElementById("myForm").submit(); ) where myForm is the id form .
2- in php, at the button level put type="submit" instead of "button".
You can retrieve the data in the page "create.php" by $_POST['terms'] and $_POST['synonym']

Problem with 'fputcsv' repeating the same variable

Iv been trying to have data from my array variables sent into a .txt file. the variables are working as intended since iv already managed to code in 3 products that a user can choose from, then use a form to submit the quantity and they all individually appear with the movie name and quantity separately. But when i cant seem to figure out a way to fputcsv send the movie names and quantity for each movie separately, i just repeats the last movie and quantity for every line, then when i submit the next movie and quantity it over-rides the last one.
My code for cart page (not showing all the code since most is css, the if/else statements were just me trying desperately to at least get the 2nd movie name out)
<?php
session_start();
?>
<?php
var_dump ($_POST);
if(!isset($_SESSION['cart'])) {
$_SESSION['cart']=[];
}
$cart = &$_SESSION['cart'];
$movieName = $_POST['movie_name'];
$quantity = $_POST['qty'];
if(isset($movieName)) {
$currentQuantity = $cart[$movieName];
$cart[$movieName] = $currentQuantity + $quantity;
} else {
$cart[$movieName] = $quantity;
}
var_dump($_SESSION);
?>
<?php
$list = array
(
"$movieName,$quantity",
"$movieName,$quantity",
"$movieName,$quantity",
);
$file = fopen("orders.txt","w");
foreach ($list as $line)
if ($movieName = 'Game of Thrones: Season 1') {
}
else if ($movieName = 'Friends Season 1') {
}
else if ($movieName = 'Inception') {
}
{
fputcsv($file,explode(',',$line));
}
fclose($file); ?>
one of the forms submitting data:
<form action="cart.php" method="post">
<input type="hidden" name="movie_name" value= "Game of Thrones: Season 1" />
<input type = "hidden" name = "id" value = "M01" />
<br>
<div class="widthc">
<button class="prod" id="minus">−</button>
<input type="number" name="qty" value="0" id="qty" min="0" max="15"/>
<button class="prod" id="plus">+</button>
<br><br>
<button class="prod" type="submit"> Submit</button>
</form>
If there is any other code u want/need to see just let me know and ill edit my post to include it. Thanks for taking the time to read.
So many little things in this code seem wrong or show just a lack of understanding. Some may be due to "sample" code.
Either way, let me go over it in chunks.
<?php
session_start();
?>
<?php
var_dump ($_POST);
Closing and opening a new PHP block is just pointless. This could be due to sample code for the question (or not). Either way it should be just :
<?php
session_start();
// debug
var_dump ($_POST);
Nothing really wrong on the next chunk. Personally I do not like it (ie; create a new var for something that already exists, even with a reference) but each to their own.
if(! isset($_SESSION['cart'])) {
$_SESSION['cart']=[];
}
$cart = &$_SESSION['cart'];
$movieName = $_POST['movie_name'];
$quantity = $_POST['qty'];
This next bit I'm not 100% confident on. You have created $movieName above from the value of $_POST['movie_name']. I believe even if that value is a blank string, your isset() will return true. Either way the result may still work as expect.
if(isset($movieName)) {
$currentQuantity = $cart[$movieName];
$cart[$movieName] = $currentQuantity + $quantity;
} else {
$cart[$movieName] = $quantity;
}
If the lodgic is sound, the following line change would remove a pointless creation of a var.
//$currentQuantity = $cart[$movieName];
$cart[$movieName] += $quantity;
Another close and open PHP block that could be removed
var_dump($_SESSION);
?>
<?php
Now to the real issue. You are creating an array with repeated elements:
$list = array (
"$movieName,$quantity",
"$movieName,$quantity",
"$movieName,$quantity",
);
The above code block would make 3 elements in the array, all with the same values - they would be all identical values of the current $movieName and $quantity.
I think what you really wanted to do was something more like:
foreach($_SESSION['cart'] as $k => $v) {
if ($v > 0) {
$list[] = array($k,$v);
}
}
This next part is interesting due to the errors. The first question is why do you hard-code a variable name?
And then the next question is did you really mean to use = instead of == in the if statement?
$file = fopen("orders.txt","w");
foreach ($list as $line) {
if ($movieName = 'Game of Thrones: Season 1') {
// do nothing? Really?
} else if ($movieName = 'Friends Season 1') {
// do nothing? Really?
} else if ($movieName = 'Inception') {
// do nothing? Really?
}
}
fputcsv($file,explode(',',$line));
fclose($file);
I think what you wanted here was more like:
// To overwrite, use 'w'
$fp = fopen('orders.csv', 'w');
// Or (as noted by Rob) to append to the file, use 'a'
//$fp = fopen('orders.csv', 'a');
// For other options see: http://php.net/manual/en/function.fopen.php
foreach ($list as $fields) {
fputcsv($fp, $fields);
}
fclose($fp);

Add to cart / Remove from cart without refreshing the page

I am new at some things and I need help about my store page.
For each item you wanna add to the cart or remove from the cart, the page refreshs and it is really annoying if you wanna buy several items.
I have read that I could use AJAX, I have read a lot of methods and nothing worked for me.
What do I need to do in order to make it work?
These are my add / remove:
<form action="" method="post">
<input type="hidden" name="item_id" value="{sid}">
<input type="hidden" name="parent" value="{parent_category}">
<input type="submit" name="atc" value="Añadir" class="sub-link">
</form>
<form action="" method="post">
<input type="hidden" name="item_id" value="{cid}">
<input type="hidden" name="parent" value="{parent_category}">
<input type="submit" name="rfc" value="Remover" class="sub-link">
</form>
And this is the function handling the submit:
function add_to_cart() {
global $db, $db_data, $db_acc, $login;
if (!empty($_POST['atc']) || !empty($_POST['rfc'])
&& isset($_GET['page']) && isset($_GET['data'])
&& $_GET['page'] == "store_shop") {
$data = $_GET['data'];
$pos = strpos($data, "-");
if ($pos == TRUE) {
$ndt = explode("-", $data);
$d1 = clean($ndt[0]);
$d2 = clean($ndt[1]);
if ($d1 == FALSE) {
$d1 = 0;
}
} else {
$d1 = 0;
$d2 = 0;
}
$sqli = $db->query("SELECT id, rname, char_db FROM $db_data.realms WHERE id='$d1'");
$numi = $db->num($sqli);
$geti = $db->get($sqli);
$cdb = $geti['char_db'];
$sqla = $db->query("SELECT id, username FROM $db_acc.account WHERE username='$login'");
$geta = $db->get($sqla);
$acid = $geta['id'];
if ($numi == 1) {
$sqlc = $db->query("SELECT guid, account, name FROM $cdb.characters WHERE account='$acid' AND guid='$d2'");
$numc = $db->num($sqlc);
$getc = $db->get($sqlc);
if ($numc == 1) {
$item = clean($_POST['item_id']);
$parent = clean($_POST['parent']);
if (!empty($_POST['atc'])) {
$sqll = $db->query("INSERT INTO $db_data.cart (`realm`, `account`, `character`, `item`, `parent`) VALUES ('$d1', '$acid', '$d2', '$item', '$parent')");
} else if (!empty($_POST['rfc'])) {
$sqll = $db->query("DELETE FROM $db_data.cart WHERE id='$item'");
}
header("Location: ?page=store_shop&data={$data}");
} else {
header("Location: ?page=store_shop&data={$data}");
}
} else {
header("Location: ?page=store_shop&data={$data}");
}
}
}
Edit: I think I am missing some details:
After clicking "add" ("Añadir" in Spanish) o "remove" ("Remover" in Spanish), the page reloads and the item is added to the cart div.
When I try the solutions I have read in stackoverflow or in other website, most of them does not work for my store and the only thing I can get is to prevent the page from reloading but the cart does not update.
Maybe should I use a iframe in the cart div?
I am still reading about ajax but I can not get it by myself.
Try this out
Remove the submit button and call the function Add to cart and same for Remove from cart using onclick="addtocart()" in anchor tag
function addtocart(){
get 'sid' and 'parent' value from anchor tag using jquery
$.ajax({
type: 'POST',
url: '/cart/add.php',
data:{ 'sid':sid, 'parent':parent }
success : function(data) { alert('success'); }
});
}
This is a form when generally causes a page load unless the default onsubmit action is overridden and the override function causes a stopPropagation on the event object. AJAX requires JS in which an XMLHttpRequest object is created (or ActiveX for IE) and communicates with server without a refresh by default ( although it can be done programatically). Then your server could return JSON for example or some indicator as to whether the call was successful and erroneous and the client side can handle it accordingly

Add to cart session not creating properly

I have created an add to cart functionality I am not pretty sure if I have developed perfectly or not.
when I am trying to add new session cart item it is not setting up for me the quantity, and pid is inserting properly, but the other two options I am unable to store though like if i try to create a variable $_SESSION['cart']['pid'].
it is working fine but when I try to add another session variable $_SESSION['cart']['option1'] it is not working
if(isset($_POST['cart'])) {
$pid = $_POST['product_id'];
$qty = $_POST['qty'];
$opt1 = $_POST['opt1'];
$opt2 = $_POST['opt2'];
if(isset($_SESSION['cart']['pid'][$pid])) {
$_SESSION['cart']['pid'][$pid]++;
$_SESSION['cart']['opt1'][$pid] = $opt1;
$_SESSION['cart']['opt2'][$pid] = $opt2;
if($qty > 1) {
$_SESSION['cart']['pid'][$pid] = $qty;
}
} else {
$_SESSION['cart']['pid'][$pid] = 1;
if($qty > 1) {
$_SESSION['cart']['pid'][$pid] = $qty;
}
}
}
<form method="POST" action="result.php">
<input type="text" name="product_id" placeholder="Product Id" />
<input type="text" name="qty" placeholder="Quantity" />
<input type="text" name="opt1" placeholder="A" />
<input type="text" name="opt2" placeholder="b" />
<input type="submit" name="cart" value="Add To Cart" />
</form>
Please let me know if I am on the right track and also the add to cart function is properly developed
I think you are confused, specially when you add an already-stored-in-session product:
When you already have the product_id in your cart, you write:
$_SESSION['cart']['pid'][$pid]++;
...so you lost the product_id from your pid session index.
Maybe you should just add the quantity in another pid -> variable ... instead of changing the pid value.
if(isset($_POST['cart'])) {
$pid = $_POST['product_id'];
$qty = $_POST['qty'];
$opt1 = $_POST['opt1'];
$opt2 = $_POST['opt2'];
// Create the prodcut_id array if it does not exist
if(!isset($_SESSION['cart']['pid'][$pid])) {
$_SESSION['cart']['pid'][$pid] = array();
}
// Is the same item already stored? (same opt1 and opt2)
$sameItem = false;
if (!empty($_SESSION['cart']['pid'][$pid])) {
foreach ($_SESSION['cart']['pid'][$pid] as $key => $product) {
// Same options item?
if ($product['opt1'] == $opt1 &&
$product['opt2'] == $opt2) {
$sameItem = $key;
}
}
}
if ($sameItem !== false) {
// Change the quantity
$_SESSION['cart']['pid'][$pid][$sameItem]['qty'] += $qty;
} else {
// Store the item as new array key
array_push($_SESSION['cart']['pid'][$pid],
array('qty' => $qty, 'opt1' => $opt1, 'opt2' => $opt2);
}
}
By the way, are you using session_start() properly?

Is there a way of updating a large form with checkboxes effectively?

Having an issue updating a large form with checkboxes effectively to database.
Just for illustration:
<form action="save.php" method="post">
<?php
for {$i=0;$i<1000;$i++) {
echo '<input type="checkbox" name="product-' . $i . '">';
}
<input type="submit">
</form>
<?php
$posted_values = $_POST;
foreach($posted_values as $key=>$p) {
$chkbox = $posted_values[$p];
$update = 0;
if ($chkbox == 'on') {
$update = 1;
}
//Do some "expensive" checking for each posted value
$save_dbarray[$key] = $update;
}
//Do the actual updating to databased based on array `save_dbarray`
Is there any way of just adding changed checkboxes to the save_dbarray? (Only checked boxes would be posted to $_POST, but I want unchecked values to be a part of the update as well if they have changed) I have to do some expensive checking for each posted value, therefore
UPDATE
I dont want to have loop through all 1000 checkboxes. I just want to loop through the changed (from checked to unchecked or from unchecked to checked) checkboxes, but in above case $posted_values would only return checkboxes that has checked values (from unchecked to checked)
<?php
//I DONT want to have to do like this:
for {$i=0;$i<1000;$i++) {
$prodnr = 'product-' . $i;
$chkbox = $_POST[$prodnr];
$update = 0;
if ($chkbox == 'on') {
$update = 1;
}
//Do some "expensive" checking for every value
$save_dbarray[$key] = $update;
}
//Do the actual updating to databased based on array `save_dbarray`
You can use HTML array inputs and PHP to do the same.
A sample code will be like below.
<form action="save.php" method="post">
<?php
for ($i=0;$i<1000;$i++) {
echo '<input type="checkbox" name="products[]" value="' . $i . '"> '. $i .'<br>';
}
?>
<input type="submit">
</form>
<?php
print_r($_POST['products']); // Will contain your desired output
foreach($_POST['products'] as $i) {
$save_dbarray[$i] = 'on'; // 'on' or whatever value if you need.
// Actually you just need $_POST['products'], no need for this loop.
}
print_r($save_dbarray);
?>
EDIT
You need to loop through $_POST['products'] to find the new checked ones and you need to loop through $already_selected to find the unchecked ones.
<?php
// Select from db or something
$already_selected = array(2,3);
foreach($_POST['products'] as $i) {
if(!in_array($i,$already_selected)){
$save_dbarray[$i] = 'checked_update';
}
}
foreach($already_selected as $j) {
if(!in_array($j,$_POST['products'])){
$save_dbarray[$j] = 'unchecked_update';
}
}
print_r($save_dbarray);
// Do db update and select again and update $already_selected to display the checked ones
?>
<form action="save.php" method="post">
<?php
for ($i=1;$i<10;$i++) {
$checked = in_array($i, $already_selected) ? 'checked' : '';
echo '<input type="checkbox" name="products[]" value="' . $i . '" ' . $checked . '> '. $i .'<br>';
}
?>
<input type="submit">
</form>

Categories