Hi! I'm trying to show 5 random images from my database and i seem to be stuck.
Would appreciate some help or tips.
I obviously dont want any duplicate images. Have tried to figure it out by googling butt my head hurts too much xD


Got thumbnails for the picture and am showing them with lightbox.

Here is the code

$result = mysql_query("SELECT * FROM imgupload");
$count = 1;

$num_rows = mysql_num_rows($result);

echo "<br />";



while ($count<=5)
{
	$query = mysql_query("SELECT * FROM imgupload ORDER BY RAND()");


$row = mysql_fetch_row($query);
$kaboom = explode("/",$row[3]);
	

echo "<a href='$row[3]' rel='lightbox[group]' title='$row[1]');><img src='$kaboom[0]/resized_$kaboom[1]'></a>";
$count = $count + 1;
				

}

I'm doing it all wrong arnt I xD

Member Avatar for diafol

Almost there:

"SELECT * FROM imgupload ORDER BY RAND() LIMIT 5"

while loop over the resultset.

I must admit, that this is slow - very slow for massive tables. Also you'd be better off naming the fields you want as opposed to using *.

Almost there:

"SELECT * FROM imgupload ORDER BY RAND() LIMIT 5"

while loop over the resultset.

I must admit, that this is slow - very slow for massive tables. Also you'd be better off naming the fields you want as opposed to using *.

I don,t really get what i'm supposed to do when you say "while loop over the resultset", care to explain?

I've been trying to compare the id of the new image with the existing ones but i have not been succesful. been trying different ways of comparing inside a loop but they all fail.

Solved it.
Thanks for the help!
I'm pertty curious tho on what other options there are instead of using "ORDER BY RAND()".


The code

<?php
include "connect.php";

$result = mysql_query("SELECT id,text,location FROM imgupload ORDER BY RAND() LIMIT 5");
$count = 0;
$num_rows = mysql_num_rows($result);

echo "<br /><table id='gallerytable'><tr>";



while ($count<=4)
{
	$row = mysql_fetch_row($result);
	$kaboom = explode("/",$row[2]);


	if ($count %5 == 0)
		{
			echo "</tr><tr>";
		}
		
	echo "<td><a href='$row[2]' rel='lightbox[group]' title='$row[1]');><img src='$kaboom[0]/resized_$kaboom[1]'></a></td>";
	$count ++;
}
	

?>
Member Avatar for diafol

The other options are quite contrived and sometimes use more than one query. For everyday use on small tables (<1000 records - a number I plucked out of the air!), it should matter much. On bigger tables, a different approach may be req'd.

If it's solved, mark it so, with the link below the edit box.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.