简体   繁体   中英

How to fetch MySQLi data order by array values?

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?

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

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 ?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM