0

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.

otis
  • 13
  • 3
  • Why are you having a `,` after your two `?`. Try to also echo $order_by and $format. – jameshwart lopez Jul 06 '16 at 10:35
  • echo is showing good variable, but the function doesn't sort by using it. I used a column between question marks cause without it PHPStorm shows me an error in code (but it doesn't have any progress if I remove it) – otis Jul 06 '16 at 10:40
  • Could you please put your current output and the expected output? – jameshwart lopez Jul 06 '16 at 10:51
  • Locked. Even if I didnť ask about SQL injection (I use PDO to prevent SQL injection. Only the function doesn't work even if I use correct name of the database column.) To your question... I dont have much data in the table, just a few rows of the names which i want to sort by the name and it doesn't work. – otis Jul 06 '16 at 11:09
  • It is not locked. It is closed because duplicate. – Your Common Sense Jul 06 '16 at 11:12
  • Anyway, I didn't ask about SQL injenction, so I don't think it is duplicate. I have some error in my function and I am unable to solve it so I asked others to help me out. – otis Jul 06 '16 at 11:32
  • Just refer to a duplicated question for an answer. As simple as that. Your case is mentioned in the accepted answer though explained in detail in my answer which is third. – Your Common Sense Jul 06 '16 at 11:48
  • solved by using whitelisting and unticking variables in the query.Thank you – otis Jul 06 '16 at 12:18

0 Answers0