I created PHP function to list all users from table and want to sort it according the column (click on column name to sort ASC/DESC)
function getAllUsers($order_by, $format) {
global $conn;
$result = array();
try {
$query = $conn->prepare("SELECT * FROM user ORDER BY ?, ?");
$query->execute(array($order_by, $format));
$result = $query->fetchAll(PDO::FETCH_OBJ);
} catch (PDOException $e) {
echo $e->getMessage();
}
return $result;
}
The PHP page is like this:
$order_by = array(1 => 'group', 'name', 'email', 'user_last_login');
$how = array(1 => 'ASC', 'DESC');
$sorting = 2;
$format = 1;
if(isset($_GET['format'])){
if($_GET['format']==1){
$format=2;
} else {
$format=1;
}
}
foreach(getAllUsers($order_by[$sorting], $how[$format]) as $user) {
echo $user->name. " ". $echo->user_last_login. "<br />";
}
The code returns me data, but it is sorted wrong (always according to the first column in the database. If I add particular name of the column to the function to be sorted data by, I get correct result. I would like to solve it by using variables in the function. Thanks for help.