How to give Loop in $ _SESSION

-1

Painted one more doubt ...

I can loop in $ _SESSION, type:

I have this code below, looping on all the images registered inside the banner table and picking up all the images registered in the image field.

<?php
$codigo = $_POST['codigo'];
$imagem = $_POST['imagem'];
$query = mysql_query("SELECT * FROM banner") or die(mysql_error());
while($res = mysql_fetch_array($query)){
?>
<label><img width="100" height="auto" src="../img_banner/<?php  echo $res['imagem'];?>" title="<?php  echo $res['imagem'];?>"/></label><br /><br />
<?php
  } 
?>

My question is if I can do the same thing with $ _SESSION, type a session with the banner name and within that session I register the amount of images you want, and pull those images through a loop.

If you have how could friends give me a light on how to run the code?

    
asked by anonymous 03.06.2016 / 17:22

1 answer

2

Of course you can:

<?php
session_start();
....
$_SESSION['banners'][] = 'imagem1.jpg';
$_SESSION['banners'][] = 'imagem2.jpg';
$_SESSION['banners'][] = 'imagem3.jpg';
...

The value of $_SESSION['banners'] here is:

Array ( [0] => imagem1.jpg [1] => imagem2.jpg [2] => imagem3.jpg )

Then you can:

foreach($_SESSION['banners'] as $banner) { ?>
    <img alt="banner" src="<?= $banner ?>">
<?php } ?>

this will produce:

<img alt="banner" src="imagem1.jpg">
<img alt="banner" src="imagem2.jpg">
<img alt="banner" src="imagem3.jpg">

Adjusting this to your code:

<?php
session_start();

$_SESSION['banners'] = array();
while($res = mysql_fetch_array($query)) { ?>
    $_SESSION['banners'][] = $res['imagem'];
    <label><img width="100" height="auto" src="../img_banner/<?php  echo $res['imagem'];?>" title="<?php  echo $res['imagem'];?>"/></label><br /><br />
<?php }

// Mais tarde quando precisar dessas imagens nesta ou noutra página faz:

foreach($_SESSION['banners'] as $banner) { ?>
    <img alt="banner" src="../img_banner/<?= $banner ?>">
<?php } ?>
    
03.06.2016 / 17:28