Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Sorting from an array

I got my data from other database, added it to an array and imploded it:

$userStr = implode("', '", $rows);

It is arranged like (‘1024’, ‘953’,’2034′), but when I try to query it and display the result:

$query = "SELECT * FROM books WHERE id in('$userStr') LIMIT $start_from, $limit";

$bookselect = mysqli_query($conn, $query);

The result will be displayed based on the arrangement of those values in ASC order.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

(‘953′,’1024′,’2034’)

Is there anyway to display the result based on its arrangement on the array?

>Solution :

MySQL supports ORDER BY FIELD(...) expression exactly for your case:

SELECT * FROM books WHERE id in('$userStr') ORDER BY FIELD(id, '$userStr') LIMIT $start_from, $limit"

P.S. A side comment for your The result will be displayed based on the arrangement of those values in ASC order reply: if you don’t specify any order, then MySQL does not guarantee any specific order. You may see ASC most of the time mostly because your MySQL query optimizer uses PRIMARY index for some internal operations. At the same time, you should never expect any specific order if you don’t mention ORDER BY in your query.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading