One problem could be that creating an array with range() and then shuffling that array is expensive: a similiar cost as using ORDER BY RAND(). Moreover, it looks like your code for selecting the random ids is not correct: you need to get the actual ids from the summary table. At the moment you appear to be using the random number generated directly to query the item_img table.
Perhaps something like this would work:
// db connection details
$db_host = '***';
$db_user = '***';
$db_pass = '***';
$db_name = '***';
// connect and select db
$dbC = mysql_connect($db_host, $db_user, $db_pass) or die(mysql_error());
mysql_select_db($db_name, $dbC);
// Insert the required IDs into the summery table based on the category id
mysql_query('INSERT INTO summary (refid) SELECT id FROM item_to_genre WHERE genre_id = '.$genreid.';', $dbC)
or die(mysql_error());
// Get the amount of records in the DB
$result = mysql_query('SELECT COUNT(*) FROM summary;', $dbC);
// create a list of random summary table ids
$max = mysql_result($result, 0) - 1;
$random_ids = array();
$i = 0;
while ($i < 8 && $i <= $max) {
$random_id = mt_rand(0, $max);
if (!in_array($random_id, $random_ids)) {
$random_ids[] = $random_id;
++$i;
}
}
$random_ids = implode(',', $random_ids);
// select the random records from the db
$sql = "SELECT id,url FROM item_img WHERE id IN(SELECT refid FROM summary WHERE id IN($random_ids))";
$result = mysql_query($sql, $dbC);
// output results
while ($row = mysql_fetch_assoc($result)) {
echo '<a href="', urlencode($row['url']), '"><img src="/images/imggals/',
(int)$row['id'], '.jpg" width="104" height="150" alt="-" /></a>';
}
// empty table ready for next summary build
mysql_query('TRUNCATE TABLE `summary`;');
// close DB
mysql_close($dbC) or die((mysql_error());
EDIT:
I suppose another way to retrieve those random records would be:
$sql = "SELECT item_img.id, item_img.url FROM item_img, summary
WHERE item_img.id=summary.refid AND summary.id IN($random_ids)";
But I have no idea if it is any better.