-1

I've been trying to make a tag that will send its outcome and store it as a php variable to I can order my mysql items by id any help at all would be highly appreciated thank you so much!

<!DOCTYPE html>
<html>
    <title>Test</title>
</head>
<body>
  <select>
    <option>Newest To Oldest</option>
    <option> Oldest To Newest></option>
    <?php
       $selection = 'ORDER BY id ASC';
       $sql = "SELECT id, threadName, message FROM threads".$selection."";
    ?>
  </select>
</body>
</html>

Bear in mind that this is only a snip-it of the code I have in total ^

Ikhlak S.
  • 8,578
  • 10
  • 57
  • 77

1 Answers1

0

Your code doesn't have form tags nor a submit button. You can use links like in the question @Mark M refereed to.

For now, lets take a look on how to do this using a combo-box.

Your HTML form would look like this:

<form method="GET">
  <select name="sort" id="sort">
      <option value="1" <?php if($selection=="ORDER BY id DESC"){echo "selected";} // if orderd by newest, selecte this ?> >Newest To Oldest</option> 
      <option value="2" <?php if($selection=="ORDER BY id ASC"){echo "selected";} // if orderd by newest, selecte this ?> >Oldest To Newest</option>
  </select>
  <input type="submit" name="submit"/>
</form>

Then your PHP script would look like this:

<?php 

$selection=isset($_GET['sort']) ? $_GET['sort'] : ""; 

if($selection == "1"){$selection="ORDER BY id DESC";}       // if selection equals to 1 then sort by newest
else if($selection == "2"){$selection="ORDER BY id ASC";}   // else if selection equals to 2 then sort by oldest
else{$selection="ORDER BY id DESC";}                        // else just sort by newest

$sql="SELECT id, threadName, message FROM threads ";        // don't forget space the end of sql
$sql.=$selection;

//echo $sql; //$sql will look like "SELECT id, threadName, message FROM threads ORDER BY id ASC "

//mysqli_query then fetch_assoc then do your loop
?>

If you intend to do the query on change of the combo-box, you can do this with the help of Javascript(jQuery) and Ajax. Take a look at this peace of code:

<script>
$(document).on('change', '#sort', function(){ // if combo-box changes do a Ajax call
    $.ajax({
        url:"url/to/script.php",              // url to your php script
        type:"GET",                           // method to use
        data:{sort: $("#sort").val()},        // parameters to send
        success: function(data){              // if this ajax call(not script) is successful then 
            $('#selector').html(data);        // add the returned data to the DOM
            }
        });
    });
</script>
Ikhlak S.
  • 8,578
  • 10
  • 57
  • 77