简体   繁体   中英

Select Box option filter

Is the following code wrong here?

I have a three option select box for different select queries for displaying data. I can't seem to get it to work. The form is submitted with a submit button with a name and value of submit. Do I need to check the select box name as well?

if(isset($_POST['submit'])) {
  if($_POST['value']=='all_records') {
    $sql = "SELECT *
        FROM contact_list
        ";
  }
  elseif($_POST['value']=='surname_desc') {
    $sql = "SELECT *
            FROM contact_list
            ORDER BY Surname DESC";
  }
  else{
    $sql = "SELECT *
            FROM contact_list
            ORDER BY FirstName ASC";
  }
$results = mysqli_query($dblink, $sql) or die (mysqli_error());
}

My form:

  <form class="filteroption" action="" method="post">
          <select class="select" name="select">
            <option value ="all_records" selected="selected">All  records</option>
            <option value ="surname_desc" selected="selected">Surname  Desc</option>
            <option value ="firstname_asc" selected="selected">First Name   Asc</option>
          </select>
            <input  class="" type="submit" name="submit" value="submit">
          </form>

The queries aren't working and changing the content of my table. I am echoing out from $results into thr table using foreach etc, which seems to work fine with the default pre query view of the page...

Replace $_POST['value'] with $_POST['select'] in all your conditions. You should use the name of the select tag to compare the values.

Also I see that you added selected="selected" for all options in select box. It should be added to only one option.

The name of your select is not "value" but "select" :

if(isset($_POST['submit'])) {
  if($_POST['select']=='all_records') {   //<=========== 'select'
    $sql = "SELECT *
        FROM contact_list
        ";
  }
  elseif($_POST['select']=='surname_desc') {   //<=========== 'select'
    $sql = "SELECT *
            FROM contact_list
            ORDER BY Surname DESC";
  }
  else{
    $sql = "SELECT *
            FROM contact_list
            ORDER BY FirstName ASC";
  }
$results = mysqli_query($dblink, $sql) or die (mysqli_error());
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM