How do I add a tag to a PHP session?

#1

How do I add ‘productID’ to the session to be different from the others?

Information that accepts

$ _POST ["pColors"]: 1, 2, 3, 4
$ _POST ["productID"]: 3, 4

Example: To get for id [3] => 1,2,3,4 and for id [4] => 1,2

if(isset($_POST['action'])) {
    if(($_POST['pColors'] != "") & ($_POST['productID'] != "")) {
        $_SESSION['productID']  = $_POST['productID'];
        foreach($_POST['pColors'] as $key => $color) {
            $_SESSION['pColors'] = $_POST['pColors'];
        }
    }
}
#2

Huh?

What do you mean by this?

If you want to track the cart information or something along those lines, then you are talking about serializing the data, or creating a cart object with everything in it and storing that.

#3

this is most helpful to you if you are trying to separate products. I think that you are trying to associate a product with a number that represents unknown data to the rest of us. What is 3,4 and 1,2 anyway? is this quantity? availability? anyway, you could try using an array as an input name or value.

when you type the following information:

you are essentially describing a key/value relationship, thus an array.
read more about arrays:
https://www.php.net/manual/en/language.types.array.php

#4

Hello! I try to ask for a product that has been added to the basket to have different selected colors.

For example, when adding a product of id 3 and obtaining the user-selected colors 1,2,3 they apply only to it, not to the subsequent products.

#5

That is entirely dependent on how you add and store that data. I for one don’t know the correlation of the colors. If I order a shirt, I don’t expect it to be added in three colors, I expect 1? If I order three shirts, then there should be a color assigned to each shirt.

<?php

class Product {
	
	private $_itemId;
	private $_size;
	private $_color;
	private $_price;
	
	
	
	public function __construct($itemID, $size, $color, $price) {
		
		$this->_itemId = $itemID;
		$this->_size = $size;
		$this->_color = $color;
		$this->_price = $price;
		
	}
	
	public function getPrice() {
		return $this->_price;
	}
	
	public function getOrderItem() {
		return "Product Id: {$this->_itemId} Size Code: {$this->_size} Color Code: {$this->_color} Price: \${$this->_price}\n";
	}
	
}



$order = [];
$order[] = new Product(1, 1, 3, 20);
$order[] = new Product(1, 1, 4, 20);
$order[] = new Product(1, 1, 2, 20);
$order[] = new Product(3, 3, 1, 50);


$total = 0;
$itemCount = 0;
foreach($order as $item) {
	echo $item->getOrderItem();
	$total += $item->getPrice();
	$itemCount +=1;
}

echo "Total items this order: {$itemCount}\nYour total is: \${$total}";

Example. Now, to store that, you would just be storing the order array to the session and use it where needed. (note that the actual data comes from the database. You would store the keys from the database as well as the quantity.)

#6

Hello!
Yes, but not in this case it is a yarn and every product has 4 or more colors. Therefore, the user selects them from them and clicks the add button in the shopping cart.
Then I take the selected colors with ajax and send them to the php code where I write them in $ _SESSION [‘pColors’]

// pick the selected colors										
	if(isset($_POST['action'])) {
		if(isset($_POST['pColors'])) {
			foreach($_POST['pColors'] as $pColors => $color) {
				$_SESSION['pColors'] = $_POST['pColors'];
			}
		}
	}												      

//Try to sort by $getProductID
	$x = $getProductID;
	foreach($_SESSION['pColors'] as $key=>$value) {
		echo ''.$x.' => '.$value.'';

		if ($key == $x) {
			echo 'Success !';
			// DB QUERY
			}
		} else { echo ' Wrong if '; }

	}
#7

so use a SESSION array. so, again, an array. SESSION variables can be created as multidimensional arrays. May i refer you again to the php manual?
https://www.php.net/manual/en/language.types.array.php

but as a SESSION array.

#8

I revised the code, now I’m recording the session through an array, but the next product added in the cart replaces the previous session.

if(isset($_POST['pColors'])) {

	$_SESSION['pColors'] = array();
	foreach($_POST['pColors'] as $colorKey => $RColors) {
		_SESSION['pColors'][$colorKey] = $RColors;
	}

}
#9

oh! i see. you are now using a SESSION array. very good! my apologies for failing to notice your new code. So now the SESSION array gets erased? well, then, we need to give this array a unique name so that you don’t replace it. I use random names for my form buttons, so maybe this will work for you in this instance. Thus:

$_SESSION['loginButton']['Name'] = base64_encode(random_bytes(12));

then you can generate a new name for the new instance of the form in order to separate the arrays and avoid erasing them. Make sense? is this helpful to you?

#10

Yes ! It is extremely useful! I added a variable that takes the id of the given product and sets it as a key.
The data I’m teaching is:

array(1) { [3]=> string(1) "4" }

Which is normal because var_dump is out of foreach - but the strange thing is that it only happens when I set $ x as a key, and when $ colorKey is not.

When I use $ colorKey data is:

array(4) { [0]=> string(1) "1" [1]=> string(1) "2" [2]=> string(1) "3" [3]=> string(1) "4" }

$ x is determined by the id of the product added to the cart.
In my opinion, it is appropriate to use it as a key.

//$getProductID > 3 or 5 in this case is 3

	$x = $getProductID;
if(isset($_POST['pColors'])) {

	$_SESSION['pColors'] = array();
	foreach($_POST['pColors'] as $colorKey => $RColors) {
		_SESSION['pColors'][$colorKey] = $RColors;
	}

}

var_dump($_SESSION['pColors']);
#11

yes the product id is appropriate. This is not the problem anyway.
We don’t want wasted time and code, so using random names is not a good idea for you because it entails tracking this name, setting and unsetting and not unsetting if needs to be persistent (which a shopping cart should be persistent throughout your session until a transaction is made or the session is terminated.)

any method that you implement must not require recoding your entire cart, so perhaps you can imagine an ideal way to assign a unique name.

without understanding your entire app, may i make a suggestion? you can ponder how it works with your current app:

create a session variable to hold a cart number. start at 1 for each session. then when the number is used to store cart info, ++session_form_id (now number 2). also offer a catch so we are not incrementing to absurd numbers (hacking). if id > x then number starts over and form error message. Then, we can use this id to append pColors. var = pColors . session_form_id which leads to session[‘pColors1’] to session[‘pColors2’] et cetera.

we just have to imagine a way to store unique product selections without recoding the entire shopping cart.

i can try to think of other ideas and maybe someone else has a better suggestion. Meantime, see if you can assign a unique name to each form access without undoing all of your hard work.

#12

Your data needs a composite index, consisting of both the product id and the color id, the same as it would/will have once the ‘order’ information has been stored in a database table. Store the entries in the session variable with this structure -

$_SESSION['cart'][$productID][$colorID] = $quantity;

The add to cart code would -

  1. Detect the ‘add to cart’ action.
  2. Validate the input data.
  3. Loop over the array of submitted color IDs/quantities and set the elements in the $_SESSION[‘cart’] array for the submitted productID value.
#13

The same would still hold, and I don’t think you need a composite, you just need an iterator.

$order = [
	0 => [
		'qty' => 1,
		'productID' => 123,
		'colors' => [
			1,
			2,
			3,
			4
			],
		],
	1 => [
		'qty' => 1,
		'productID' => 133,
		'colors' => [
			2,
			4,
			7
			],
		],
	2 => [
		'qty' => 1,
		'productID' => 312,
		'colors' => [
			1,
			5,
			8,
			11
			],
		],
	];
 
 
foreach($order as $key => $value) {
	echo '<pre>';
	print_r($value);
	echo '</pre>';
}	

And all of this can be stored in the session array with just,

$date = new DateTime();
$_SESSION[$date->format('Y-m-d')] = $order;

Need to add something to it?

array_push($order, $product);

It all depends how you design the product class

1 Like
#14

i didn’t think of that and i forgot about array_push. i’m still a novice Master astonecipher :slight_smile: good work!

#15

I tried to rotate the code without rewriting everything with one extra key and rotating everything together for each separate one.

    $i = 0;
    foreach($_SESSION['pID'] AS &$getProductID) {

    	$x = $getProductID;
    	if(isset($_POST['pColors'])) {

    		$_SESSION['pColors'] = array();
    		foreach($_POST['pColors'] as $colorKey => $RColors) {
    			$_SESSION['pColors'][$colorKey][$x] = $RColors;
    		}

    	}
    	$i++;
    }

    	echo $x;
    	echo '<pre>';
    	 print_r($_SESSION['pColors']);
    	echo '</pre>';

$_SESSION['pID']:

    Array
    (
        [0] => 3
        [1] => 5
    )

$_SESSION['pColors']:
3
    Array
    (
        [0] => Array
            (
                [5] => 3
            )

        [1] => Array
            (
                [5] => 4
            )

    )

5
Array
(
    [0] => Array
        (
            [5] => 3
        )

    [1] => Array
        (
            [5] => 4
        )

)
#16

Why are you using an alias by reference???


You should still have alphanumeric keys so you know what things are.

#17

I’m sorry! I removed it.
I swapped out the places of $ colorKey and $ x and I think it’s right to structure the array. Still, the question revolves around why it rotates the cycle again and replaces the values ​​rather than rotating it with the next productID

Array
(
    [5] => Array
        (
            [0] => 1
            [1] => 2
            [2] => 3
            [3] => 4
        )
)
#18

Where are you adding the products to the session

#19
<?php
ob_start();
session_start();

if(isset($_POST)) {

	if(isset($_SESSION['pID']) AND isset($_SESSION['pQua']) AND isset($_SESSION['ip']) AND isset($_SESSION['ua'])) {

		$arrayPID = array();
		$arrayPQua = array();
		
		$arrayPID = $_SESSION['pID'];
		$arrayPQua = $_SESSION['pQua'];
		
		$arrayPID[] = htmlspecialchars(addslashes($_POST['pID']));
		$arrayPQua[] = htmlspecialchars(addslashes($_POST['pQua']));
		
		$_SESSION['pID'] = $arrayPID;
		$_SESSION['pQua'] = $arrayPQua;
		
	} else {
		$arrayPID = array();
		$arrayPQua = array();
		
		$arrayPID[] = htmlspecialchars(addslashes($_POST['pID']));
		$arrayPQua[] = htmlspecialchars(addslashes($_POST['pQua']));

		$_SESSION['pID'] = $arrayPID;
		$_SESSION['pQua'] = $arrayPQua;
		$_SESSION['ip'] = $_SERVER['REMOTE_ADDR'];
		$_SESSION['ua'] = $_SERVER['HTTP_USER_AGENT'];

	}
}

?>

#20

I played with the code yesterday and I came to the conclusion that if the array is declared outside this if it will not overwrite. But the problem is that when I pull it out if it does not record anything in it. It remains empty