Answer the question
In order to leave comments, you need to log in
How to sort?
Good afternoon! there is this code
$limit = 'limit 0, 500';
if (isset($_GET['ajax2'])) $limit = 'limit '.(int)$_GET['offset'].', 30';
$rows = fs::getObjects($sql, "order by c_object.added desc ".$limit);
$rowsCount = count(fs::getObjects($sql));
if (isset($_GET['ajax2']) && !count($rows))
{
header("HTTP/1.0 404 Not Found");
die;
}
Answer the question
In order to leave comments, you need to log in
Add two more parameters to the sort part of the query.
order_column - which column to sort by, order_direct - in which direction.
The limit example hints at how to do this.
$limit = 'limit 0, 500';
$order_column = 'added';
$order_direct = 'desc';
if(isset($_GET['order_col']))
{
if($_GET['order_col'] == 'updated')
$order_column = 'updated'; // не вздумайте подставлять из GET название колонки, будет sql-инъекция!
}
if(isset($_GET['order_dir']))
{
if($_GET['order_dir'] == 'asc')
$order_direct = 'asc'; // не вздумайте подставлять из GET название клаузы, будет sql-инъекция!
}
if (isset($_GET['ajax2'])) $limit = 'limit '.(int)$_GET['offset'].', 30'; // тут застраховано от инъекции при помощи преобразования в int!
$rows = fs::getObjects($sql, "order by c_object.".$order_column." ".$order_direct." ".$limit);
$rowsCount = count(fs::getObjects($sql));
if (isset($_GET['ajax2']) && !count($rows))
{
header("HTTP/1.0 404 Not Found");
die;
}
function orderBy(array &$array, $sortOrder)
{
usort($array, function ($a, $b) use ($sortOrder) {
$result = '';
$sortOrderArray = explode(',', $sortOrder);
foreach ($sortOrderArray AS $item) {
$itemArray = explode(' ', trim($item));
$field = $itemArray[0];
$sort = !empty($itemArray[1]) ? $itemArray[1] : '';
$mix = [$a, $b];
if (!isset($mix[0][$field]) || !isset($mix[1][$field])) {
continue;
}
if (strtolower($sort) === 'desc') {
$mix = array_reverse($mix);
}
if (is_numeric($mix[0][$field]) && is_numeric($mix[1][$field])) {
$result .= ceil($mix[0][$field] - $mix[1][$field]);
} else {
$result .= strcasecmp($mix[0][$field], $mix[1][$field]);
}
}
return $result;
});
return $array;
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question