Reputation: 337
I'm currently facing a problem displaying results by a limit, my query ends in ORDER BY date DESC limit $limit
and my html code is
<select name="limit" id="limit">
<option value="5">5</option>
<option value="10">10</option>
<option value="15">15</option>
<option value="20">20</option>
</select>
In my PHP I have $limit=$_POST["limit"];
Now, this is basically working, except that on page load the form containing limit
isn't posted, so I get a query error until I change the value of limit and submit it.
How can I have a default value selected on initial page load?
Upvotes: 0
Views: 968
Reputation: 1477
Is this you are looking for
On page load selected="selected" takes default value.
<option value="15" selected="selected">15</option>
In PHP
if(isset($_POST['limit']) && !empty($_POST['limit'])) {
$limit = $_POST['limit'];
} else {
$limit = '5'; /* Your default value*/
}
In Query, try something like this
ORDER BY date DESC limit ".$limit;
Upvotes: 1
Reputation: 316
$_POST['limit']
will not exist until limit
is posted e.g. by form submission.
If you want a default, I suggest:
$limit = filter_var($_POST['limit'], FILTER_VALIDATE_INT);
if(empty($limit) || !$limit) $limit = 10;
Then bind $limit to your prepared statement - assuming that's what you're using.
If you're not using prepared statements then you'd better check the content of $_POST['limit']
before concatenating it into a SQL statement like other posts here are suggesting.
Upvotes: 0
Reputation: 8809
you can use the conditional check in PHP
like this
$limit=isset($_POST["limit"])?$_POST["limit"]:5; // or change the value which you want to show onload
Upvotes: 0
Reputation: 43
You can test if the variable is empty then set it to a default value.
$limit = $_POST["limit"];
if ($limit == '') $limit = 5;
Upvotes: 1
Reputation: 15773
Set $limit
to a default value like 0 and change it only if there's a posted value:
$limit = 0;
if(isset($_POST["limit"])) $limit = $_POST["limit"];
Also note that you shouldn't paste user input in queries since this could lead to sql injection.
Upvotes: 1