PDA

View Full Version : arrays and mysql


8utt
Wed 8th Nov '06, 12:11pm
I have a field in my users table which contains a comma seperated list of values corresponding to the ids of another table.

What I need is a mysql query that will give me the table contents in the order of the seperated list.

An example is.

user.pictures = 0,5,8,4,2,7,90,87

in the php I give this the value $userpictures

I want a query which looks like

select * from pictures where id IN $userpictures

The problem is that it returns the pictures but in the order 0,2,4,5,7,8,87,90

Is there a way of returning the data in the same order as it is listed in the user table field ?

Hope this makes sence.

Many Thanks

Marco van Herwaarden
Wed 8th Nov '06, 12:16pm
You can always add an ORDER BY to the query.

8utt
Wed 8th Nov '06, 12:29pm
yes but order by what ?

I cannot do order by asc or desc ?

the values I'm asking for are 0,5,8,4,2,7,90,87

so I want them ordering by 0,5,8,4,2,7,90,87

how do you do this ?

Marco van Herwaarden
Wed 8th Nov '06, 12:49pm
Sorry there is no way you can get that order with MySQL.

8utt
Wed 8th Nov '06, 12:57pm
Is there a way of reordering the data I get from mysql with php.

Say the array I want is 0,5,8,4,2,7,90,87

I run the mysql and get 0,2,4,5,7,8,87,90

Then do something in php to resort the array by 0,5,8,4,2,7,90,87

by the mysql would contain 3 data fields

Id , Filename, Text.

All I'm after really is putting something (an array) into a while loop to go through and give me the pictures in the order above (0,5,8,4,2,7,90,87)

Marco van Herwaarden
Wed 8th Nov '06, 1:15pm
You could put all the table rows into an array like:
$data_array[$sql_result[id]] = $sql_result;

Then loop through the list of ID's with a foreach and use that array element.