0

I'm storing a multiple selection on page 1 PHP and would like to get the selected values in cookies/session.

<select multiple="multiple" name="subjects" size=3 multiple>
<option value="math">Mathematics
<option value="sci">Science
<option value="his">History
</select>
<?php
setcookie('subjects', $subjects);
?>

I would like to get the selected values in a page 2 PHP and print out some links:

<html>
<body>
<?php
if(isset($_COOKIE["subjects"])){
    if ($_POST['subjects.value = math']) {
        echo "https://en.wikipedia.org/wiki/Mathematics, https://www.niu.edu/mathmatters/everyday-life/index.shtml, https://en.wikipedia.org/wiki/Areas_of_mathematics <br />";
    }
    if ($_POST['subjects.value = sci']) {
        echo "https://en.wikipedia.org/wiki/Science, https://en.wikipedia.org/wiki/Biology, https://en.wikipedia.org/wiki/Chemistry <br />";
    }
    if ($_POST['subjects.value = his']) {
        echo "https://en.wikipedia.org/wiki/History, https://en.wikipedia.org/wiki/History_of_Macau, https://en.wikipedia.org/wiki/History_of_Malaysia <br />";
    }
}
?>
</body>
</html>
  • Why don't you just actually submit a form with the select and output accordingly. – Markus AO Apr 10 '22 at 15:52
  • or add a change event on the input then fire off ajax to get the links, using cookies is not the solution, also setcookie('subjects', $subjects); is not going to work until you fill $subjects which would require to post the form anyway. Additionally, you could plop all them links into js object then you don't need php at all – Lawrence Cherone Apr 10 '22 at 15:54
  • this is a requirement for me to use either session or cookie to save the values and retrieve them in another php. – FRY1999 Apr 10 '22 at 15:59

1 Answers1

0
<select multiple="multiple" name="subjects" size=3 multiple>
<option value="math">Mathematics
<option value="sci">Science
<option value="his">History
</select>
<?php
setcookie('subjects', $subjects);

foreach ($_GET['subjects'] as $selectedsubject)
    echo $selectedsubject."\n";
?>

try that above but also you can check here for reference How to get multiple selected values of select box in php?

tillinberlin
  • 429
  • 4
  • 14
deo_gemini
  • 25
  • 8
  • I would like the user to select subjects (can be more than one) then print out some links as suggestion for user. So the cookie is store is first PHP and the coding for echo is in second php. – FRY1999 Apr 10 '22 at 15:47
  • As it’s currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Apr 10 '22 at 16:36