0

I have a form that submits data. Let's for example say it submits this data:

    Age     => 23
    Gender  => Male 
    Country => UK

Now I need to store this in a session array, that I have already made. BUT, this array already exists AND contains more fields than are given by the first form. For example, this is what the session array could look like:

    Age => Value
    Gender => Value
    Country => Value
    State => Value
    Language => Value

As you can see, only the first 3 are given with the first form. I would like a for each loop that detects which values are given (in this case: age, gender and country) and then place those values within the session array.

For example, the next form would give the information:

    State => Value
    Language => Value

I've been trying to wrap my head around this, but I just can't find a solution.. :/

1

1 Answer 1

0

Something like:

$valid_fields = array('Age', 'Gender', 'Country', 'State', 'Language');
foreach ($_POST as $key => $value) {
    if (in_array($key, $valid_fields)) {
        $_SESSION[$key] = $value;
    }
}
Sign up to request clarification or add additional context in comments.

7 Comments

Hey, it doesn't seem to be working. I use that same code, with a different array name but here's what I get when I dump the $_POST array: array(6) { ["mysqlname"]=> string(4) "root" ["mysqlpass"]=> string(4) "root" ["mysqlhost"]=> string(9) "localhost" ["mysqldatabase"]=> string(3) "pfs" ["mysqlport"]=> string(4) "3306" ["seed"]=> string(32) "837ec5754f503cfaaee0929fd48974e7" } and this is what my $_SESSION looks like: The value of $_SESSION['mysqlname'] is '' The value of $_SESSION['mysqlpass'] is '' .... not full.. but you get the idea.. it stays empty
That makes no sense. $_POST is always initialized with the form field values. I don't see how all the MySQL stuff could be getting into it, you must have some other code in your script that's doing this.
Oh wait, I just noticed I did stuff in the wrong order. Let me remake my code and then I'll come back to you with my findings.
You're misunderstanding how var_dump displays values. That means it has the value "root", which is a string that's 4 characters long.
Where is the Age, Gender, Country stuff that you said was in your form input?
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.