Home » Php » php – Two questions about ORDER BY using Prepared Statements

php – Two questions about ORDER BY using Prepared Statements

Posted by: admin February 25, 2020 Leave a comment

Questions:
<?php
$what = 'creationdate';

$sql = "SELECT * FROM `accountlist` ORDER BY ? [ASC/DESC]";

$stmt = $conn->stmt_init();

if(!($stmt->prepare($sql)))
{
  echo "Error";
} else {
  $stmt->bind_param("s", $what);
  $check = $stmt->execute();
  $result = $stmt->get_result();
}

for($n=1; $row = $result->fetch_assoc(); $n++)
{
  var_dump($row);echo "<br />";

  echo $n . ':<br />';
  foreach($row as $key => $value) echo $key . ': '. $value . '<br />';
  echo '<br />';
}

echo $check ? 'success' : 'error/no lines'

?>

  1. Why does this return the same result when I use either ASC or DESC in my query?
  2. Is there a way to place a placeholder instead of that *? Using a ? and binding it returns a “?” in the $row array…
How to&Answers:

This is a bit long for a comment.

You cannot replace an identifier in a SQL statement using a parameter. Examples of identifiers are column and table names. You also cannot replace SQL keywords or operators, such as INNER or =.

In your case, you are substituting a parameter with a constant value. It is treated as the value, not as a column reference (or expression). Hence, ASC and DESC do not differentiate among equal values.