0

I have a table named desserts with ID's, but when I use the IN clause , it returns a sorted result.

  public function getDessertById($id)
    {
        $stmt = $this->conn->prepare("SELECT * FROM `desserts` WHERE id IN (" . $id . ");");
        $stmt->execute();

        return $stmt->fetchAll();
    }

whenever the id is an array of (55,23,1,5,7,12) it always returns (1,5,7,12,23,55)

Zhorov
  • 28,486
  • 6
  • 27
  • 52
  • Chances are that "id" is the primary key on the table, and sql will then inherently sort its returned results in that order. That's just the nature of a primary key – Craig Apr 15 '21 at 07:02
  • Table may be indexed by key 'id' – hoangnh Apr 15 '21 at 07:02
  • You'd likely need to do some fiddling on the PHP side, after you're retrieved the records, and build your own array of "results" that follows the "id" sequencing of your original array (for whatever the reason is that you want to maintain that same order). Alternatively, if there's another column that it makes sense to sort by (eg. sort the "name" of the desserts alphabetically), then stick an ORDER BY name ASC in your SELECT statement – Craig Apr 15 '21 at 07:04

0 Answers0