-2

I have created an array, it is used to fetch data from MySQL server.

$ids = array(249853, 245549, 249851, 245552, 245551, 249854, 245550, 282445, 261747, 249852, 222398, 248072, 248390, 272473, 219212, 234140, 249815, 241089, 271940, 274940);

$sorted_ids = implode($ids, ",");

Fetched data using $sorted_ids which is ID to retrieve, but it is retrieved data by ID ascending order

$sql = "SELECT ID, number FROM table WHERE ID IN ({$sorted_ids})";
$result = mysqli_query($connection, $sql);

I have tried using == but it is showing only indexes matched records others not.

$i = 0;
while($row = mysqli_fetch_assoc($result)) {
    if( $ids[$i] == $row['ID'] ) {
        echo $row['ID']."<br>";

        $i++;
    }
}

It is showing records if both indexes matched not other records.

How can I display records by $ids array list ?

3
  • 2
    What are you actually trying to achieve? Your code as you say will print out each ID you have retrieved when it matches the ID from your array... Are you wanting the data to be printed in order of the ID's in the array? Commented Jun 28, 2021 at 8:52
  • @Zachary yes, exactly Commented Jun 28, 2021 at 9:36
  • 1
    @Zachary I wanted to print data in order of the IDs in the array Commented Jun 28, 2021 at 9:41

1 Answer 1

1

Easiest way to do what you want is to the order it within your SQL

$sql = "SELECT ID, number FROM table WHERE ID IN ({$sorted_ids}) ORDER BY FIELD(id, {$sorted_ids})";

Should do the trick

Sign up to request clarification or add additional context in comments.

1 Comment

it is ordering data by the array values perfectly, thank you

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.