1

I have a simple array $ids e.g. (2,9,4,10,18). And also I've got a mysql table $table1 with the same IDs as primary keys. My question is: how to select the elements in my table in THE SAME ORDER as the IDs go in my array using just 1 query (I don't what to call the query by every ID number of an array, because the table is supposed to have a lot of entries).

Still, if you can give me another way to do it, I would like to know it.

1

2 Answers 2

1

If you use string instead of array then:

<?php
 $arr="2,9,4,10,18";
 $query =   mysql_query("SELECT * FROM  tablename WHERE id IN ($arr)");
 while($row=mysql_fetch_array($query)){ 

 //display data here

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

2 Comments

Looks interesting! I'm going to try it out.
Works.. But 50/50. Because it just selects all the entries in a list, but not in a custom order. When I try "18,2,4,9,10", it still gives me "2,9,4,10,18" in $row.
0

create a temporary table with two columns, the id row and the position order.

then run your query like this :

select t.* from table t 
inner join #temp t2 on t.id = t2.id
where t.id in (select id from #temp)
order by t2.position

You should create a SP for this, can't say if you can with mysql

1 Comment

Another table is not an option, because, as I said earlier, there would be a lot of entries + this function is going to be used very often. I want something easy and fast.

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.