Home > Software engineering >  Using the values of a var inside a foreach loop
Using the values of a var inside a foreach loop

Time:11-13

I'm working on a lms system and I'm having this problem

foreach($datas as $data){ ?>
   <div style="background-color: #3B4FDF; border-radius: 3%; width: 30%; height: 220px; margin-right: 5%; cursor: pointer;" onclick="location.href='classAdmin_list.php'">
     <p style="font-size: 1.5vw; color: white; position: relative; left: 7%; top: 0%;"> <?= $data['class_name'] ?> </p>
     <p style="font-size: 1vw; color: white; position: relative; left: 75%; top:  -25%;"> <?= $data['class_code'] ?> </p>
     <p style="font-size: 1vw; color: white; position: relative; left: 7%; top: 17%;"> <?= $data['school'] ?> </p>
<?php $_SESSION['className'] = $data['class_name']; ?>
     <img src="foto/balll.png" alt="ball" style="opacity: 0.5; width: 22%; height: 100px; position: relative; left: 75%; top: -30%;">
  </div>
<?php } ?>  

This is a code that creates a divs that look like this: enter image description here

Those roman numbers are names. Im currently saving them inside a $_Session that is inside a foreach loop. And that is exactly the problem.

When i click the div it redirects me to a page that looks like this: enter image description here

U see that (I-2).

I need that I-2 to be the class name (roman number) based on the div that it got clicked.

But that value is being saved on a $_Session, and that $_Session gets updated and overwrites previous values. so if i click on the 1 div (XII-3) it wont say : "Class XII-3" but "Class I-2".

Here is the code i use to make that "Class X"

<p>
      Class <span><?= $_SESSION['className'] ?></span>
</p>

I saw some questions but they were using for each loops so im asking because i cant find an answer

CodePudding user response:

This is not a good use case for sessions. Just pass the name in the URL as a query parameter:

onclick="location.href='classAdmin_list.php?name=<?= urlencode($data['class_name']) ?>'">

(Always use urlencode() when adding values the the URL to make sure they won't break the URL)

and then use that on the classAdmin_list.php-page:

Class <span><?= htmlentities($_GET['name']) ?></span>

(Always use htmlentities() or htmlspecialchars() when outputting data to protect against XSS)

CodePudding user response:

you need to wrap the img in some sort of anchor for example

<a href="/selected.php?className=<?=urlencode($data['class_name'])?>">
    <img src="foto/balll.png" alt="ball" style="opacity: 0.5; width: 22%; height: 100px; position: relative; left: 75%; top: -30%;">
</a>
  • Related