I have a date filter for entries from database. On the first page i have a list of all entries. On the second i have the same filter and almost filtered by date list. So i want to keep values of filter from the first page.
Here is my code :
<form action="filter.php" method="post">
<label>From</label><input name="from" required="true" type="date"/>
<label>To:</label> <input name="to" required="true" type="date"/>
<input name="" type="submit" value="Search" />
</form>
<table>
...
...
...
</table>
</div>
You can access the variable after pressing submit.. Therfore you have to change <input name="" type="submit" value="Search" />
to <input name="submit" type="submit" value="Search" />
<?php
if(isset($_POST['submit'])) {
$from = $_POST['from'];
$to = $_POST['to'];
}
?>
You can also store the variable into sessions, to access it from everywhere.
<?php
session_start();
if(isset($_POST['submit'])) {
$from = $_POST['from'];
$to = $_POST['to'];
$_SESSION['from'] = $from;
$_SESSION['to'] = $to;
}
?>
The third option would be, to set the method of the form element to method="GET"
. After that you can access the values through:
<?php
if(isset($_GET['submit'])) {
$from = $_GET['from'];
$to = $_GET['to'];
}
?>
With the get Parameter you can also do a magic thing like: http://www.example.com/index.php?from=20150906&to=20150907. So you get the values of the variable via the URL..
For more information see: http://php.net/manual/en/reserved.variables.php
I hope I could help you...
In your case, since you are using POST
, you can access the values
if(isset($_POST['submit']])) {
$from = $_POST['from'];
$to = $_POST['to'];
}
As user Markus already said, you should change your submit-button
name-attribute to a self-explanatory name, to keep it easy to maintain the code and check, if this button was pressed.
You then have to set it via the value
-attribute in your form.
<form action="filter.php" method="post">
<label>From</label><input name="from" value="<?php echo $from; ?> required="true" type="date"/>
<label>To:</label> <input name="to" value="<?php echo $from; ?>required="true" type="date"/>
<input name="submit" type="submit" value="Search" />
</form>
Keep in mind, that it is never safe to pass unsanitized data. So you should consider sanitizing the user input. (for instance a given format like YYYY-MM-DD)