Satish
Satish

Reputation: 41

Session not passing dropdown selected element to other php script

First php script -

<?php
 session_start(); 
?>

<html>
<head>
</head>
<body><form method = "post">
<select name="feature" id="feature">
        <?php
        ?>
        <option value > Select Feature</option>
        <?php
        foreach($newFeature as $feat)
        {
            ?>
        <option value="<?php echo $feat;?>"><?php echo $feat;?></option>
            <?php
       }
         ?>
</select>
</form>
</body>
</html>

<?php
    $_SESSION['feature'] = $feature;    
 ?>

second php script -

<?php
session_start(); 
echo $_SESSION['feature'];
?>

When I run second php script, I get Array as echoed element instead of the element I selected. What is wrong with the logic here ?

Please guide.

Upvotes: 0

Views: 771

Answers (1)

GuyT
GuyT

Reputation: 4416

You have to submit the select. It is impossible to set $feature at that moment because the user hasn't yet selected anything.

<form method = "post">
<select name="feature" id="feature">
        <option value > Select Feature</option>
        <?php foreach($newFeature as $feat) : ?>
           <option value="<?php echo $feat;?>" <?= $feat == $_SESSION['feature'] : " selected = 'selected'" : "" ?>><?php echo $feat;?></option>
        <?php endforeach; ?>
</select>
<input type="submit" value="send" name="mySubmit" />
</form>

When you hit 'send' you can get the value by using $_POST['feature']; on the same page. If you want to go to another page you have to set the form action property.

session_start();
$_SESSION['feature'] = $_POST['feature'];

After the submit the page will 'reload'. Check if mySubmit is set and set the $_SESSION['feature'](don't forget to start your session at top of the page):

if (isset($_POST['mySubmit'])){
   $_SESSION['feature'] = $_POST['feature'];
}

Upvotes: 2

Related Questions