-3

I found an example of storing an input field from a form to session data, but can't figure out how to store a selected field from a select/option field of a form. I currently have:

<strong>Choose your model:</strong>
   <form action="" method="post">
       <select name="cars">
        <option value="camry" name="camry">Camry</option>
        <option value="corolla" name="corolla">Corolla</option>
        <option value="rav4" name="rav4">RAV4</option>
        <option value="tacoma" name="tacoma">Tacoma</option>
    </select>

    <input type="submit" name="Submit" value="Submit!" />
</form>


<?php 

// starting the session
session_start();

This is where I get confused:

if (isset($_POST['Submit'])) { 
  $_SESSION['cars'] = $_POST['cars'];
  } 
?> 

<strong><?php echo $_SESSION['cars'];?></strong>

Any help would be great. Thank you!

mrmills129
  • 51
  • 1
  • 10

3 Answers3

2

Your Code does not contain any error and it will work fine.

You can use the isset() while calling it over to the code and hence it avoid the errors that display up in your browser.

Replace:

<strong><?php echo $_SESSION['cars'];?></strong>

With:

<?php
session_start();
ob_start();
error_reporting(0);// This will depreciate all errors  
if(isset($_SESSION['cars']))
{
echo '<strong>'.$_SESSION['cars'].'</strong>';
}
else
{
// Handle failure over here
}
?>

But as you have mentioned that you have got confused at the session() am explaining about the session and the form attributes that you have used below.

Explanation

Will provide you with the clear explanation of what the process happens.

One:

if (isset($_POST['Submit'])) {}

This will handle up the form submit operation. Once after the form is submitted this action will take place.

Provided the name of the submit button should be as name="Submit" and then it will trigger up this action on submit of the form.

Two:

<select name="cars"></select>

When you need to fetch out the data after the form is submitted you need to provide with the name for the select tag then alone you can get the data from the option that is being selected.

Three:

<option value="camry" name="camry">Camry</option>

Option does not contain the name in the HTML and you have to delete the name which you have provide to the option tag.

Four:

After all this is over we are now going for the session_start() in the PHP.

session_start — Start new or resume existing session.

session_start() creates a session or resumes the current one based on a session identifier passed via a GET or POST request, or passed via a cookie.

When session_start() is called or when a session auto starts, PHP will call the open and read session save handlers. These will either be a built-in save handler provided by default or by PHP extensions (such as SQLite or Memcached); or can be custom handler as defined by session_set_save_handler(). The read callback will retrieve any existing session data (stored in a special serialized format) and will be unserialized and used to automatically populate the $_SESSION superglobal when the read callback returns the saved session data back to PHP session handling.

To use a named session, call session_name() before calling session_start().

When session.use_trans_sid is enabled, the session_start() function will register an internal output handler for URL rewriting.

Reference: http://php.net/manual/en/function.session-start.php

How to Use Sessions in Your PHP Scripts

  1. Starting a Session
  2. Storing and Accessing Variables
  3. Ending a Session
Naresh Kumar P
  • 4,127
  • 2
  • 16
  • 33
  • 1 - OP already using `name="Submit"` 2 - already using name attribute for select box, 3 - this is not an issue but valid point, 4 - Ohh, its working fine on my end :p – devpro Oct 10 '16 at 14:53
  • @devpro. I am explaining him for this alone in his question: `This is where I get confused:` – Naresh Kumar P Oct 10 '16 at 14:56
  • you wrote too much here and isn't the real issue here. What I wrote [in a comment](http://stackoverflow.com/questions/39960778/store-data-from-form-to-session-as-variable#comment67201909_39960778) I wrote up there, is the "real" answer here ;-) Just saying. – Funk Forty Niner Oct 10 '16 at 15:01
  • @devpro. I have added `isset()` and `error_reporting()` and that will suppress the error – Naresh Kumar P Oct 10 '16 at 15:04
  • @Fred -ii. I have added `isset()` and `error_reporting()` and that will suppress the error . Added `error_reporting()` as per your advice. – Naresh Kumar P Oct 10 '16 at 15:05
  • @NareshKumar.P Thank you for the explanation. I am trying to learn about this stuff in the few minutes I have of free time a day, so I appreciate you taking the time. Thank you again. – mrmills129 Oct 12 '16 at 14:48
0

When the <form> is submitted, only the selected value in <select> is posted. This is how you get the selected value in $_POST['cars'].

Aakash Martand
  • 926
  • 1
  • 8
  • 21
0

As others stated, option should not have a name. Your code is working as expected. The $_POST data will be written to $_SESSION variable after pressing submit. The select box will then be reset to camry as HTML is a stateless protocol.

session_start() should also be the first line if you want to make use of session variables.

To wrap it up:

<?php
session_start();
?>

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title></title>
</head>
<body>
    <strong>Choose your model:</strong>

    <?php
    $cars = ["camry", "corolla", "rav4", "tacoma"];
    ?>        
    <form action="" method="post">
        <?php
        if (isset($_POST['Submit'])) {
            $_SESSION['cars'] = $_POST['cars'];
        }
        ?>
        <select name="cars">
            <?php
            foreach ($cars as $car) {
                $selected = "";
                if (isset($_SESSION['cars']) && $_SESSION['cars'] == $car) {
                    $selected = "selected='selected'";
                }
                // select car based on session variable
                echo "<option value='$car' $selected>$car</option>";
            }
            ?>
        </select>

        <input type="submit" name="Submit" value="Submit!" />
    </form>

    <strong>
        <?php if (isset($_SESSION['cars'])) {
            echo $_SESSION['cars'];
            ?>
        }
    </strong>
</body>

vaultboy
  • 173
  • 1
  • 1
  • 12