问题
On my list.php
page, the user can choose a country from the drop-down to show the SQL server's data for the selection. On this selection, the user gets the option to update/edit the values on an edit.php
page. When the user submits the changes on the edit.php
page, they are redirected to a save.php
page and then back to the initial list.php
page. I was wondering if it's possible to use the SESSION
variable to store the initial country selection so the user gets the same selection when redirected to list.php
. I've tried to use session_start ();
, but couldn't get it to work.
EDITED
This are pieces of my code:
Top of list.php
:
<?php session_start(); ?>
Form:
<form name="frmname" id="frmid" action="list.php" method="POST" >
<h4>From: <input type="text" size="6" name="start_date" pattern="[0-9/]+"
placeholder=" 00/00/0000" />
To: <input type="text" size="6" name="end_date" pattern="[0-9/]+"
placeholder=" 00/00/0000" />
<select name="RegioSelect" onchange="this.form.submit();" ><option><?php echo $_SESSION['RegioSelect']; ?></option>
Dropdown populated by:
$query1 = "SELECT DISTINCT CountryRegionName FROM tKein23 ORDER BY CountryRegionName";
$stmt1 = $conn->query( $query1 );
while ($data = $stmt1->fetch(PDO::FETCH_ASSOC)){
echo '<option value="'.$data['CountryRegionName'].'">';
echo $data['CountryRegionName'];
echo "</option>";
}
Then I tried SESSION_START()
:
<h4><input type="submit" value="Show" name="Selection" />
</select>
</form>
<?php
if(isset($_POST["RegioSelect"])){
$_SESSION['RegioSelect'] = $_POST["RegioSelect"];
}
Now, on other pages, I do get the $_SESSION['RegioSelect']
variable. On list.php
, I get the variable in the drop-down but no submission.
回答1:
session_start() must come first, before any other ouput. Not only before html on your php script, but before any browser output.
PHP Documentation
To use cookie-based sessions, session_start() must be called before outputing anything to the browser.
<?php session_start(); ?>
<html>
<body>
...
...
<h4><input type="submit" value="Show" name="Selection" />
</select>
</form>
<?php
if (isset($_POST["RegioSelect"]))
$_SESSION['RegioSelect'] = $_POST["RegioSelect"];
回答2:
If the form is on the same page, make sure to move the
if (isset($_POST["RegioSelect"]))
$_SESSION['RegioSelect'] = $_POST["RegioSelect"];
to the top - right below the session_start()
and before the <html>
otherwise you have to reload the page first - which is probably not what you want
from there on you can also do redirects to other pages via header()
来源:https://stackoverflow.com/questions/46384283/dropdown-selected-value-in-a-session-variable-accross-different-pages-doesnt-pe