问题
I am trying to post a form to $wp_session which is working fine - however when I perform it again it overwrites the array that I have put there in the first place, I need the arrays to carry on building up like a collection / shopping basket.
My form:
<form class="form1" method="post" action="" id="form1">
<fieldset>
<ul>
<label for="name">Exercise ID</label><span>
<input type="text" name="ExerciseID" placeholder="Exercise ID" class="required" role="input" aria-required="true"/></span>
<label for="name">Exercise Reps</label><span>
<input type="text" name="Sets" placeholder="Sets" class="required" role="input" aria-required="true"/></span>
<label for="name">Exercise Reps</label><span>
<input type="text" name="Reps" placeholder="Sets" class="required" role="input" aria-required="true"/></span>
<input class="submit .transparentButton" value="Next" type="submit" name="Submit"/>
</ul>
<br/>
</fieldset>
</form>
And the php:
<?php
global $wp_session;
if (isset($_POST['Submit'])) {
$wp_session['collection'] = array($POST['ExerciseID'],$_POST['Sets'],$POST['Reps']);
}
print_r($wp_session);
?>
Many thanks in advance.
回答1:
To have a basket, you have to add the products to an array:
<?php
global $wp_session;
if (isset($_POST['Submit'])) {
$wp_session['collection'][] = array($_POST['ExerciseID'],$_POST['Sets'],$_POST['Reps']);
}
print_r($wp_session);
?>
You may want to organize the array by ExerciseID, so you can add to the quantity. I would advice you to create some objects, as they will be more flexible than arrays
回答2:
Maybe you are looking for this: instead of overwriting you append a new entry to your "session variable" at each run:
<?php
global $wp_session;
if (isset($_POST['Submit'])) {
$wp_session[]['collection'] = array($_POST['ExerciseID'],$_POST['Sets'],$_POST['Reps']);
}
print_r($wp_session);
?>
Note the additional []
in the left hand side of the assignment.
来源:https://stackoverflow.com/questions/22895443/wp-session-variables-being-overwritten-by-post