View Full Version : Resolved PHP Random Image Query

08-12-2008, 04:35 PM
Hi Guys,

I need to create a random image to be generated on a home page I am doing.

Basically I need to put three random images in three seperate boxes on the homepage.

These images need to be based on a category id.

1. Bi-Folding doors
2. Windows and Doors
3. Conservatories.

The image (image1) is in a table called portfolio, the cat_id is in the portfolio table and linked with portfolio_cat table.

I need the code for the following

get image1 from portfolio table where its cat_id is = 1,2 or 3 and limit that to just one image to view.

I have this piece of code which generates random images I just don't know how to change it to do what I need.

Here is the code

mysql_select_db("$database", $dbh);
$sql = "SELECT * FROM portfolio ORDER BY ????????? RAND() LIMIT 1";
$query = mysql_query($sql, $dbh) or die ("Error in query: $sql" . mysql_error());

//Now we loop through each record returned.
while ($row = mysql_fetch_array($query))

//get values from database
$id = $row['??????']; //usually database record id

//now generate using above values - note html <option>
echo $row['??????'];

}//end of loop


Can anybody help with this?

I have a feeling the echo statement might need to change also so if anybody could do the code for that then that would be great.



08-12-2008, 05:00 PM
$sql = "select * from portfolio where cat_id = 1 order by RAND() limit 0,1";

08-12-2008, 05:33 PM
Thanks for your reply.

But that query does not include where i am pulling the image from

would it not be

$sql = "SELECT image1 FROM portfolio WHERE cat_id=1 ORDER BY RAND() limit 1";

So if the above query is correct...how would I echo it into my html???

08-12-2008, 10:31 PM
I'm assuming your holding the IMAGE PATH, not the actual image in the database.

$sql = "SELECT image1 FROM portfolio WHERE cat_id=1 ORDER BY RAND() limit 1";
$result = mysql_query($sql) or die('Could not look up user data; '.mysql_error());
$db_info = mysql_fetch_assoc($result);
echo "<img src=\"".$db_info['image1']."\">";

08-13-2008, 10:12 AM

There is an image folder on the server.

The database just links the path.

Thanks for the help.

08-14-2008, 10:33 AM
Hi guys

thanks for all your help.

Here is the final code that works great.


mysql_select_db("$database", $dbh);

$sql = "SELECT image1 FROM portfolio WHERE cat_id=1 ORDER BY RAND() Limit 1";

$query = mysql_query($sql, $dbh) or die ("Error in query: $sql" . mysql_error());

while($row = mysql_fetch_array($query))


echo "<img src=\"images/".$row['image1']."\">";

} // End of while loop