Reputation:
There is a mistake causing it not to flip between ASC/DESC and I am 90% sure it is within these few lines.. I think I need to have a "first" loop that will "save" $sort so it flips later. But when I do this it causes an array error then.
The SQL is more than likely correct... I am NOT worried about SQL Injections/PDO/security yet as I am adding that code in later.
Full Link: https://solenoidal-slate.000webhostapp.com/
if(isset($_GET['sort'])){
$sort = $_GET['sort'];
} else {
$sort='ASC';
}
$sort == 'DESC' ? $sort ='ASC': $sort='DESC';
$query = "SELECT * FROM employees ORDER BY $order $sort";
$results = mysqli_query($con, $query); ?>
<th><a class="column_sort" id="id" href='?order=id&sort=$sort'>ID<span class="glyphicon glyphicon-sort-by-alphabet"></span></a></th>
This above line is an example of a column that is "Getting" the $sort variable.
EDIT: To save time, $order is not the issue.. Each column name is sorting by column successfully.
if(isset($_GET['order'])){
$order = $_GET['order'];
} else {
$order = 'id';
}
Upvotes: 2
Views: 2704
Reputation: 499
Your final code would be something like this:
if (isset($_GET['order'])) { // Check $_GET['order'] is in the predefined array
$order = $_GET['order'];
} else {
$order = 'id';
}
if(isset($_GET['sort'])) { // Preferably you can check this also in_array($_GET['sort'], ['ASC', DESC])
$sort = $_GET['sort'];
} else {
$sort = 'ASC';
}
$query = "SELECT * FROM employees ORDER BY $order $sort";
$results = mysqli_query($con, $query);
Your link needs to be changed,
It should be like this http://solenoidal-slate.000webhostapp.com/?order=id&sort=DESC or ASC and remove one &
from the link
Now it's like this: https://solenoidal-slate.000webhostapp.com/?order=id&&sort=$sort
Upvotes: 0
Reputation:
Do:
$sort = ($sort == 'DESC') ? 'ASC': 'DESC';
and write only one "&" between query string key/value pairs:
<a ... href="?order=id&sort=$sort">
and apply php code properly in the "href". Otherwise you'll have $sort
as html code too.
So, I would do it like so for example:
<?php
$order = isset($_GET['order']) ? $_GET['order'] : 'id';
$sort = isset($_GET['sort']) ? $_GET['sort'] : 'ASC';
$sort = ($sort == 'ASC') ? 'DESC': 'ASC';
$query = "SELECT * FROM employees ORDER BY $order $sort";
$results = mysqli_query($con, $query); ?>
//....
?>
<th>
<a class="column_sort" id="id" href="?order=id&sort=<?php echo $sort; ?>">
ID<span class="glyphicon glyphicon-sort-by-alphabet"></span>
</a>
</th>
Or you could use this directly:
<?php
//...
$sort = ((isset($_GET['sort']) ? $_GET['sort'] : 'ASC') == 'ASC') ? 'DESC' : 'ASC';
$query = "SELECT * FROM employees ORDER BY $order $sort";
//...
Upvotes: 1