How can I get the output of records from the database in the sequence in which the id records are transferred (my records are constantly output sequentially 1 - 5).

$connect= mysql_connect("localhost", "testing", "testing"); $select = mysql_select_db("testing", $connect); mysql_query("SET NAMES utf8"); $id = "5,2,1,4,3"; $result = mysql_query("SELECT * FROM products WHERE id IN ($id)"); while ($data = mysql_fetch_row($result)) { echo "<H1>$data[0] ........."; echo "$data[2]<br></H1>"; } 

    1 answer 1

    To do this, you can use the MySQL function FIELD() , which returns the position of the occurrence of the first argument in the list, which is set by the remaining arguments. Pass the value from the id field as the first parameter, and use the values ​​from the $id list as the remaining arguments. The result of the function is passed to the keyword ORDER BY , which sorts the results of the sample.

     $connect= mysql_connect("localhost", "testing", "testing"); $select = mysql_select_db("testing", $connect); mysql_query("SET NAMES utf8"); $id = "5,2,1,4,3"; $result = mysql_query( "SELECT * FROM products WHERE id IN ($id) ORDER BY FIELD(id, $id)" ); while ($data = mysql_fetch_row($result)) { echo "<H1>$data[0] ........."; echo "$data[2]<br></H1>"; } 
    • Thank. I knew a lot about ORDER BY , but I never used FIELD() . - Php-2016