Hi all,

I have a shopping basket feature on my website which saves the product's primary key in the session array called 'cart', each one seperated by a comma, so example: '123,456,789'.

Now in order to get each item from my shopping basket to paypal I need to write 2 hidden form fields onto the page containing the product name and price, however if the user has more than one of the same item, I want it to write a hidden field for the quantity instead of simply writting the same product over and over again.

Here is the script i currently have:

$cart = $_SESSION['cart'];
$items = explode(',',$cart);
foreach ($items as $pid) //pid is the product's primary key
	{
		$i = $i + 1;
		$pricequery = mysql_query('SELECT * FROM products WHERE pid = "'.$pid.'"');
		while($price = mysql_fetch_array($pricequery))
		{
			echo'<input type="hidden" name="item_name_'.$i.'" value="'.$price['name'].' '.$price['series'].' '.$price['manufacturer'].'"><input type="hidden" name="amount_'.$i.'" value="'.$price['price'].'"><input type="hidden" name="quantity_'.$i.'" value="'.$qty.'">';
		}
         }

As you can see from the code, $qty has not been set. This is where I am having my difficulty. I was thinking for each product you could add it's PID into an array then check if the pid is in the array before deciding wether or not to write the quantity, however the problem occurs when having to go back and change the quantity field that has been echo'd because another product with the same PID has been found in the cart array.

Sorry for the lenghty description etc! I hope somebody has the time to help, so thanks in advance.

Max

Dani AI

Generated

As noted, the right idea is to count identical PIDs and emit one set of PayPal fields per unique product instead of repeating the same product lines. A cleaner, safer approach is to turn the session string into an integer array, use PHP's built-in counter to get quantities, fetch all product rows in one query (avoid N queries in a loop), then output the indexed PayPal fields.

// $pdo is an existing PDO connection
$ids = array_filter(array_map('intval', explode(',', $_SESSION['cart'] ?? '')));
if ($ids) {
    $counts = array_count_values($ids);
    $unique = array_keys($counts);

    $placeholders = implode(',', array_fill(0, count($unique), '?'));
    $stmt = $pdo->prepare("SELECT pid, name, series, manufacturer, price FROM products WHERE pid IN ($placeholders)");
    $stmt->execute($unique);
    $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
    $byPid = [];
    foreach ($rows as $r) { $byPid[(int)$r['pid']] = $r; }

    $i = 1;
    foreach ($unique as $pid) {
        if (!isset($byPid[$pid])) { continue; }
        $p = $byPid[$pid];
        $name = trim($p['name'].' '.$p['series'].' '.$p['manufacturer']);
        $amount = number_format($p['price'], 2, '.', '');
        echo '<input type="hidden" name="item_name_'.$i.'" value="'.htmlspecialchars($name).'">';
        echo '<input type="hidden" name="amount_'.$i.'" value="'.$amount.'">';
        echo '<input type="hidden" name="quantity_'.$i.'" value="'.$counts[$pid].'">';
        $i++;
    }
}

Notes and cautions: cast PIDs to integers to avoid injection, use prepared statements (shown), escape HTML attributes with htmlspecialchars, and format prices with number_format to two decimals. Do not trust client-submitted amounts—validate totals on the server side (IPN/PDT or similar) before fulfilling orders. For long-term robustness, store the cart as an associative array (pid => qty) in the session rather than a comma list; that makes updates and quantity edits trivial. For counting, see PHP's documentation on array_count_values (array_count_values()).

dont worry, iv figured it out. Do something like this:

explode the cart into an array.
foreach($cart as $pid)
{
if the pid is in the array, do nothing
else: use substr_count to get the QTY
echo
add pid to array
}

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.