0

I'm having troubles with my Order by in MySqli in PHP. It either the bind_param not working for or something else. I not sure what I'm forgetting here, it just doesn't want to accept my bind. Thanks in Advance.

 @ $db = new mysqli('localhost', 'root', '', 'books');
    // if mysqli_connect_errno() is set, we did not successfully connect. Here we deal with the error.
    if (mysqli_connect_errno()) {
        echo 'Error: Could not connect to database.  Please try again later.</body></html>';
        die();
    }
    $sortOrder = 'title';

    $query = "SELECT ISBN, Author, Title, Price FROM books ORDER BY ?";
    $stmt = $db->prepare($query);
    $stmt->bind_param('s', $sortOrder);

    $stmt->execute();
    $stmt->store_result();
    $stmt->bind_result($isbn, $author, $title, $price);

    echo "<p>Number of books found: " . $stmt->num_rows . "</p>";

    $counter = 0;
    if ($stmt->num_rows > 0) {
        while ($stmt->fetch()) {
            $newBook = new book($isbn, $author, $title, $price);
            $bookList[$counter] = $newBook;
            $counter++;
        }
    } else {
        //Nothing
    }
    $stmt->free_result();
    $db->close();
Branderson20
  • 176
  • 1
  • 3
  • 13

1 Answers1

1

You can't bind identifiers (tables/columns), you can only bind values. Use a whitelist to check the value is one of a known pair then pass it in if it is.

if(in_array($column, array('title', 'possible_other_column'))) {
     $query = "SELECT ISBN, Author, Title, Price FROM books ORDER BY $column";
     $stmt = $db->prepare($query);
     $stmt->execute();
} else {
     echo 'Column is not a valid name please select a valid column';
     //or whatever behavior you want to happen, maybe just use a default column
user3783243
  • 5,368
  • 5
  • 22
  • 41
  • Thanks you for this, It's help me figure it out – Branderson20 Dec 03 '18 at 05:03
  • This makes sense. Interpolation is used for interpolation of values, not column names. For example, `WHERE id = ?` would have to be converted to `WHERE id = "177"`. So mysqli probably just interpolates without even checking any SQL syntax. Which means that `ORDER BY ?` would become `ORDER BY "title"`, which is wrong. – David Knipe Feb 16 '19 at 22:24