twan twan - 3 months ago 8
MySQL Question

Add ids as array in a session and return products according to ids inside it

I'm trying to add multiple products to a session, and then at a quote page display all the products in that session.

How I'm doing it:

Link to quote page which sends the productid with it:

<p><a class="offertelink" href="offerte.php?product='.$productcr[0]['id'].'">Request a quote</a></p>


Then on the quote page I put it in a session:

$_SESSION['product'] = $_GET['product'];


But this only remembers one product, what if I go back to add another product, then only that new product is displayed instead of both products that I added.

I want to save all id's in a session and then inside a query display all the saved products by using
id IN ('1', '2', '3')


With the id's being the productids that are send by clicking the link.

I tried a couple of things like turning the session into an array but still it only remembers one product id. I have session_start at the top of a file I include everywhere.

$_SESSION['product'] = array();

Answer

Simply check if $_SESSION['product'] already exist. If not create it as an ARRAY. Then add all subsequent IDs to the $_SESSION['product'] Array like this: $_SESSION['product'][] = $_GET['product'];. That way, you are sure to have an array of IDs when ever you try to access $_SESSION['product']

<?php //<==  NOTICE THAT THERE IS NO WHITE SPACE BEFORE "<?php"

    // FIRST CHECK IF SESSION EXIST BEFORE STARTING IT.
    // DO THIS AT THE VERY TOP OF EACH SCRIPT THAT NEEDS ACCESS TO $_SESSION DATA
    if (session_status() == PHP_SESSION_NONE  || session_id() == '') {
        session_start();
    }

    // DO THIS ON THE PAGE WHERE YOU ARE SETTING THE IDs INTO THE $_SESSION
    if( !isset($_SESSION['product'])){
        $_SESSION['product'] = array();
    }

    $_SESSION['product'][] = $_GET['product'];

UPDATE: Get the String Value for use in Database

<?php

    if( !isset($_SESSION['product'])){
        $_SESSION['product'] = array();
    }

    // CHECK FIRST THAT $_GET['product'] IS SET BEFORE ADDING IT TO SESSION
    if( isset($_GET['product']) ){
        $_SESSION['product'][] = $_GET['product'];
    }

    // IN THE FILE THAT USES THE DATA FOR DATABASE TRANSACTIONS,
    // YOU CAN DO THIS:
   // THE $valuesForDB WOULD CONTAIN SOMETHING LIKE: '2','7','10','12','13'
    $valuesForDB    = "'" .  implode("','", $_SESSION['product']) . "'";


    var_dump($valuesForDB);  //<== PRODUCES::: string ''2','7','10','12','13'' (length=22) [FOR EXAMPLE]

    var_dump($_SESSION['product']);
    // PRODUCES SOMETHING LIKE:::
    array (size=5)
      0 => int 2
      1 => int 7
      2 => int 10
      3 => int 12
      4 => int 13