Search code examples
phparrayssession-variables

how to save in a session variable an array extracted from a database to send it to other web pages in php


I have some data than I recoved from a database in a treatment page and than i try to send these data to other web pages by a session variable, like that :

while($enr = mysqli_fetch_assoc($res))
{
    $_SESSION['med'] = $enr;

    header("location: recherche.php");

    //print_r($_SESSION['med']);
}

when I print_r($_SESSION['med']); in the processing page, I have an array like that :

Array ( [nom] => CASPER [prenom] => ARMAND ) 
Array ( [nom] => WILLIAMS [prenom] => GEORGE ) 
Array ( [nom] => VANASTEN [prenom] => ROBERT ) 
Array ( [nom] => MARTIN [prenom] => ALAIN ) 
Array ( [nom] => Jacque [prenom] => ERIC ) 
Array ( [nom] => LUCAS [prenom] => ANNIE )

But when I try to retrieve this array of data to other pages like that :

<?php
        if (isset($_SESSION['med'])) {
            foreach ($_SESSION['med'] as $champ) {
                echo "$champ -----";
            }
        } else {
            echo "no data";
        }
?>

I only have the last like that :

LUCAS -----ANNIE -----

So, how can I do to have all the data ?


Solution

  • The reason why your print_r looked good is that you put into the loop. You rewrite the $_SESSION['med'] variable every row and the last row was your result what you get back when you print out your session later.

    You should try this:

      while($enr = mysqli_fetch_assoc($res))
        {
            $_SESSION['med'][] = $enr;
    
    
    
    
        }
    //print_r($_SESSION['med']);
    header("location: recherche.php");
    

    And then:

    if (isset($_SESSION['med'])) {
            foreach ($_SESSION['med'] as $champ) {
                echo $champ['nom']." -----";
             }
     } else {
          echo "no data";
     }