Liberator Liberator - 2 months ago 10x
HTML Question

HTML Form Select default value from PHP Echo _Post

I have a html form where people select to filter the mysql results, example

<select name="display">
<option value="9999" selected>Display all results</option>
<option value="10">10 results only</option>
<option value="20">20 results only</option>
<option value="50">50 results only</option>
<option value="100">100 results only</option>

But if people select lets say 50 results per page, after form submit I want the option 50 results only to get marked as selected like this

<option value="50" selected>50 results only</option>

The question is How to do this using PHP POST or GET from the form


As I said in comments, assign a variable to a POST array and set it in your LIMIT in the query.

// you can also use isset instead of empty here and GET instead of POST
if(!empty($_POST['display'])) {
    $limit = (int)$_POST['display']; // ensure the value is an integer

Then place the $limit variable in your query for LIMIT.

I.e.: (and as basic MySQL)

SELECT col1, col2, col3 FROM TABLE WHERE col_x = 'xxx' LIMIT $limit

The question though is a bit unclear so there isn't much else I can add to this.

Sidenote: LIMIT (with SELECT) accepts additional parameters. I.e.: LIMIT 0, 50

[LIMIT {[offset,] row_count | row_count OFFSET offset}]


"after form submit I want the option 50 results only to get marked as selected"

In order to keep the value selected, use a conditional statement in the select's options and check if it equals to something:

Sidenote: This will only work if your entire code is inside the same file.


    if(!empty($_POST['display'])) {
        $limit = $_POST['display'];
        $selected = 'selected';


<form action="" method="post">
    <select name="display"> 
    <option  value="9999" <?php if(isset($selected) && $limit==9999 ) {echo $selected; } ?>>Display all results</option>
    <option  value="10" <?php if(isset($selected) && $limit==10) {echo $selected; } ?>>10 results only</option>
    <option  value="20" <?php if(isset($selected) && $limit==20){echo $selected; } ?>>20 results only</option>
    <option  value="50" <?php if(isset($selected) && $limit==50){echo $selected; } ?>>50 results only</option>
    <option  value="100" <?php if(isset($selected) && $limit==100){echo $selected; } ?>>100 results only</option>

<input type="submit" value="submit">


You can add in the rest of your code.