How to Loop $_SESSION

Asked

Viewed 162 times

-1

painted yet another doubt...

I can loop in $_SESSION, like:

I have this code below, looping all the images registered inside the banner table and taking 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 whether I can do the same thing with $_SESSION, like create a banner-named session and within that session I register the amount of images you want, and pull these images through a loop.

If I have how friends could give me a light on how to execute the code?

1 answer

2

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

Despois 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 } ?>
  • Thanks Miguel, but I ask you one more question. When registering new images, would it always create a new name for the registered image and include this new image in the loop automatically? I’m sorry for the abuse, but I was left with this doubt...

  • I will edit with the value that $_SESSION['banners'] would have

Browser other questions tagged

You are not signed in. Login or sign up in order to post.