how to get random image from mysql dabase

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
sanjaypandit
Forum Newbie
Posts: 2
Joined: Tue Jul 14, 2009 12:31 pm
Contact:

how to get random image from mysql dabase

Post by sanjaypandit »

I am facing a problem this time.

i want to show up random image from a database where these field are image1, image2, image3 chk attachment

now i want to show up these images randomly

Code: Select all

<? $query=mysql_query("select * from tbl_property where prop_id='5'");
    $rsToGetPass=mysql_fetch_array($query);
 
 
                 if(($rsToGetPass['image1'] <> "") or ($rsToGetPass['image2'] <> "") or ($rsToGetPass['image3'] <> "")){
                
                <img  src ="images/property/mem_pics/<? echo  [color=#BF0040]$rsToGetPass['image1'][/color] ;?>" width="189" height="145">
            
                <? } elseif (($rsToGetPass['image1'] == "") && ($rsToGetPass['image2'] == "") && ($rsToGetPass['image3'] == "")){?>
                <img src = "admin/images/no_pic.jpg" width="189" height="145" border="0">
                <? }?>
 

i want to show up image randomly image1, image2, image3 (currebtly showing image1----color in red) there is also a problem if image1 is blank then it should be show either image2 or image 3,, if image 2 is blank then it show image1 and image3

thanks
Attachments
tbl_property.zip
mysql table
(972 Bytes) Downloaded 1 time
Last edited by sanjaypandit on Fri Nov 06, 2009 3:36 am, edited 1 time in total.
davegmpd
Forum Newbie
Posts: 14
Joined: Tue Oct 27, 2009 9:42 am
Location: London

Re: how to get random image from mysql dabase

Post by davegmpd »

Code: Select all

 
 
$query=mysql_query("select * from tbl_property where prop_id='5'");
$rsToGetPass=mysql_fetch_array($query);
 
// create array of "active" images; eg: non-blank ones
$aImgs = array('image1', 'image2', 'image3');
$aActiveImgs = array();
foreach ($aImgs as $sImg)
{
   if (!empty($rsToGetPass[$sImg]))
      $aActiveImgs[] = $sImg;
}
 
// grab one randomly
if (count($aActiveImgs) > 0)
{
   shuffle($aActiveImgs);
   $sActiveImg = array_pop($aActiveImgs);
}
else
{
   $sActiveImg = null;
}
 
// output
if (!is_null($sActiveImg)) :
?>
 
<img src ="images/property/mem_pics/<? echo $rsToGetPass[$sActiveImg] ;?>" width="189" height="145">
 
<?php else : ?>
 
<img src = "admin/images/no_pic.jpg" width="189" height="145" border="0">
 
<?php endif; ?>
 
 
Should do it.

Dave
sanjaypandit
Forum Newbie
Posts: 2
Joined: Tue Jul 14, 2009 12:31 pm
Contact:

Re: how to get random image from mysql dabase

Post by sanjaypandit »

Thanks Boss its work !
Post Reply