How do I add a tag to a PHP session?

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.)

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 '; }

	}

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.

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;
	}

}

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?

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']);

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.

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.

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

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

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
        )

)

Why are you using an alias by reference???


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

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
        )
)

Where are you adding the products to the session

<?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'];

	}
}

?>

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

Rather than continue down this line, what exactly needs to be stored? As in, if an order was going to be made, what details would you need at this step?

Hello!
Well, it must store the color id and the number of the color.
Each product can have an unlimited number of colors. Hearing is quite specific as we are talking about yarn and it is bought in a ball and for this reason certain colors (orbs) are ordered from the yarn.

		function filter_data() {

			var action = 'fetch_data';
			var pColors = get_filter('pColor');

		    $('.addToCart').click(function(){
		        $.ajax({
	                url:""+realLink+"cart.php",
	                method:"POST",
	                data:{action:action,pColors:pColors},
		                success:function(data){
		                   //alert(data);
		                }
            	});
		    });

		}

I have not added the number of colors, because the addition of colors, camels and the number to send it is not yet working: D

You seem to be adding a product to the cart and then selecting the color(s) and quantity(ies) as a separate step, without providing a way of relating the data that’s submitted in the second step with the product it belongs with. Submitting the product id as part of the second step would solve your immediate problem.

Why not use a single step that lets you pick a product and the color(s) and quantity(ies) all at once. See the following example code -

<?php
session_start();

// post method form processing
if($_SERVER['REQUEST_METHOD'] == 'POST')
{
	switch($_POST['action'])
	{
		case 'C':
			// Create - add to cart
			
			// examine the submitted data
			// echo '<pre>'; print_r($_POST); echo '</pre>';
			
			// you would validate the input data here...

			// add the products to the cart
			foreach($_POST['qty'] as $color_id=>$quantity)
			{
				if($quantity > 0)
				{
					$_SESSION['cart'][$_POST['product_id']][$color_id] = $quantity;
				} else {
					// zero (or negative) quantity, remove product from the cart
					unset($_SESSION['cart'][$_POST['product_id']][$color_id]);
				}
			}
		break;
		
		// code for other actions here...
	}
}
?>

<?php
// display the cart
if(empty($_SESSION['cart']))
{
	echo 'The cart is empty.<br><br>';
} else {
	// using the product id's from the cart (see array_keys()) you would retrieve all the product names, descriptions, and prices needed to display the cart
	echo 'Your cart contains:<br>';

	// for demo purposes, display the raw cart data
	ksort($_SESSION['cart']); // sort by product id
	foreach($_SESSION['cart'] as $product_id=>$arr)
	{
		ksort($arr); // sort by color id
		echo "Product $product_id<br>";
		foreach($arr as $color_id=>$quantity)
		{
			echo "Color $color_id, Quantity $quantity<br>";
		}
		echo '<br>';
	}
	echo '<br>';
}
?>

<?php
// product display/selection - product id, color id, and quantity

// fake 10 products for demo purposes
foreach(range(1,10) as $product_id)
{
	// display product information here - name, description, price, image ...

	// for demo purposes, display the product id only
	echo "Product $product_id<br>";
	// add to cart form
	echo "<form method='post'>";
	echo "<input type='hidden' name='action' value='C'>"; // Create - add to cart
	echo "<input type='hidden' name='product_id' value='$product_id'>";
	// you would output only the color ids and color names for the current product. this example code uses the same color ids 1-4 for all products
	echo 'Select a non-zero quantity for each color you want to order.<br>';
	// fake 4 colors for demo purposes
	foreach(range(1,4) as $color_id)
	{
		// get the existing quantity, if any, from the cart
		$quantity = $_SESSION['cart'][$product_id][$color_id] ?? 0;
		// for demo purposes, display the color id only. in your real code display the color name and/or a color image
		echo "Color $color_id Quantity <input type='number' name='qty[$color_id]' value='$quantity'><br>";
	}
	echo "<input type='submit' value='Add To Cart'></form><br><br>";
}
1 Like

this code from phdr is perfect! stick with this design.

Sponsor our Newsletter | Privacy Policy | Terms of Service