View Full Version : Random Directory Script

12-17-2008, 05:46 PM
Hello all,

Ok so I have a script that pulls category names from a database. I then fetch it from the db and print the category using a while loop inside that same while loop I print out each of the corresponding items that belong in that category within another while loop. So the category gets printed then the items in it.

My problem is I want the categories to randomly change order on page refresh which means the items also have to change order. I was toying with storing it all in arrays and shuffle() them but then how do you know which items go with which category after because the shuffle() assigns new keys...

Anyways heres my code the items always have to be under the category they belong and the categories should appear randomly on refresh:

$query = "SELECT name,id
FROM category
WHERE id='1'";

$mysql_stuff = mysql_query($query, $mysql_link);
while($row = mysql_fetch_row($mysql_stuff)) {
// populate the variables from the parent table for a single record

$category = $row[0];
$id = $row[1];


$query2 = "SELECT name
FROM restaurants
WHERE category_id='$id'";

$mysql_stuff2 = mysql_query($query2, $mysql_link);
while($row2 = mysql_fetch_row($mysql_stuff2)) {
// populate the variables from the parent table for a single record

$restaurants = $row2[0];



Here is the sample of it working:


I need Italian to switch places with casual dining on refresh.

12-17-2008, 07:00 PM
I though I would add that it can be done in javascript also if someone can think of a better way. The reason for this is restaurants are paying for this and I get the feeling that if I don't switch things around a lot people will complain that there below the fold and paying as much as the ones above the fold so I need some sort of random ordering.

12-17-2008, 07:21 PM
Never mind I got it!

In case anyone is wondering for future reference I created another column in my category table called order_by and gave it a unique value for each of the categories. I then create an array called order and put items 0-11 in the array.

I then shuffle that array and made a for loop to update the order_by column in my category table then I use the sql order by and I use the column order_by when ordering my categories.

The id stays the same so I just use that to place the right items in the right categories and voila I am randomly choosing the order of my stuff.