The following code displays random database images as well as one specific image (which is what I want). How can I shuffle these results after database query as image ID 11 is always displayed first? I want image ID 11 displayed randomly amongst the others.
Can I use SHUFFLE(). If so where exactly do I put it as at the moment?
Any help would be appreciated as still learning PHP
Thanks.
<?php
mysql_connect("", "", "") or die(mysql_error()) ;
mysql_select_db("images") or die(mysql_error()) ;
$photo=mysql_query("SELECT * FROM `profile_images` ORDER BY (ID = 11) DESC, RAND()
LIMIT 7");
while($get_photo=mysql_fetch_array($photo)){ ?>
<div style="width:300px;">
<img src="<? echo $get_photo['url']; ?>">
</div>
<? } ?>
You can shuffle them after they are retrieved to php.
$photos = array();
while ($get_photo = mysql_fetch_array($photo))
$photos[] = $get_photo;
shuffle($photos);
Or you can do it with subqueries:
SELECT A.* FROM (
SELECT * FROM `profile_images`
ORDER BY (ID = 11) DESC, RAND()
LIMIT 7
) as A
ORDER BY RAND()
Its doesnt need to be that complicated if you just put for example
SELECT * FROM tbl_table ORDER BY RAND()
This will randomise your data. if you want to limit out how many images you show then just put:
SELECT * FROM tbl_table ORDER BY RAND() LIMIT 6
rand()
all the rows get unique random value to sort so the subgroups aren't sorted. So using more columns in order by clause does not work if there is rand()
present. Hence I have used alias the result and sort it again.See the query
(SELECT *
FROM `profile_images`
WHERE id = 11
LIMIT 1)
UNION
(SELECT *
FROM (SELECT *
FROM `profile_images`
WHERE id != 11
ORDER BY Rand()
LIMIT 6) `t`
ORDER BY id DESC)
First select the image with ID 11 and than query the rest with UNION keyword
SELECT *
FROM Images
Where ID = 11
UNION
SELECT *
FROM Images
WHERE ID != 11
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With