PHP - Random Image
The purpose of this function is to go to the characters table and grab all of the characters that have a statusID of one however I want it to limit it to any ONE of those characters as this is a random image it's going to show and then I want it to have that charactes shortName and then use it to find their spotlight image from inside of the images/spotlight folder. All its showing right now in its spot is the the filename of the image when I call this function.
function spotlight(){ $query = "SELECT * FROM characters WHERE characters.statusID = 1 LIMIT 1"; $result = mysql_query($query); $row = mysql_fetch_assoc($result); $labels = array('shortName'); $img = array(); if($handle = opendir('images/spotlight/')) { $count = 0; while (false !== ($file = readdir($handle))) { if(strlen($file) > 2){ $img[$count] = $file; $count++; } } } echo $img[rand(0, (count($img)-1))]; } Similar TutorialsIm Am Trying To Display A Random Image Every Time The Page Refreshs i dont know if this will help??? <?php /* User Pets (user_pets.php) */ $rank_check = 1; $page_title = "User Pets"; include "header.inc.php"; print $openHTML; $array = fetch("SELECT * FROM user_pets2 WHERE id = '$id' AND game = '$game'"); if (!$array[id]) { die("<p align=center class=error>That is not a real pet</p>$closeHTML"); } if ($array[pet_desc]) { $petNote = "<tr><td colspan=2><p align=center><font size=-1><i>$array[pet_desc]</i></font></p></td></tr>"; } print "<center><table>$petNote<tr> <td width=200> "; $id = $array[id]; $getPet = fetch("SELECT * FROM pets2 WHERE id = '$array[species]' AND game = '$game'"); $getOwner = fetch("SELECT display_name,username FROM members2 WHERE id = '$array[owner]' AND game = '$game'"); $image = "pet_$getPet[id]"; if ($array[wearing] != 0) { $findLook = fetch("SELECT * FROM pet_looks WHERE change_from = '$array[species]' AND item_name = '$array[wearing]'"); if ($findLook[id]) { $image = "pet2_$findLook[id]"; } } $hunger = $array[$hunger]; $hungerLevel = $hungerArray[$hunger]; if (($array[hunger] > 10) OR ($array[hunger] < 0)) { $hungerLevel = "Unknown ($array[hunger])"; } $percentHealth = ($array[current_hp] / $array[max_hp]) * 100; if ($percentHealth > 0) { $healthLine = "<font color=red>$array[current_hp]/$array[max_hp]</font>"; } if ($percentHealth > 35) { $healthLine = "<font color=orange>$array[current_hp]/$array[max_hp]</font>"; } if ($percentHealth > 75) { $healthLine = "<font color=green>$array[current_hp]/$array[max_hp]</font>"; } ECHO <<<END <br> <CENTER><TABLE BGCOLOR="#$tableOutline" CELLSPACING=1 CELLPADDING=0 WIDTH=400> <tr> <td colspan=2 bgcolor=#$topAndBottomBG><font color=#$topAndBottomText><b>View Pet:</b></font></td></tr> <TR> <TD BGCOLOR=#$middleBG> <p> <font size=-1> Name: $array[name]<br> Level: $array[level]<br> Experience: $array[experience]<br> Next Level: $nextLevel[$id]<br> Health: <b>$healthLine</b><br> Strength: $array[strength]<br> Intelligence: $array[intelligence]<br> Speed: $array[speed]<br> Defense: $array[defense]<br> Hunger: $hungerLevel<Br> </font> </p> <p> <font size=-1> 1-Player Wins: $array[one_p_wins]<br> 1-Player Loses: $array[one_p_loses] </font> </p> </TD> <TD WIDTH=175 BGCOLOR=#FFFFFF> <p align=center> <img src=$base_url/images/user_images/opg_$game/pets/$image.gif border=1> <br><a href=view_pet.php?id=$array[id]&game=$game><b>$array[name]</b> the $getPet[name]!$petNote[$id]</a></P> <p align=center>$attitude[$id]</p> </TD> </TR> </TABLE> </CENTER> <p align=center><a href=user_profile.php?game=$game&user=$getOwner[username]>Back to $getOwner[display_name]'s Profile!</a></p> END; print "$closeHTML"; ?> Please Help Me Jackthumper Hi Everyone, I was wondering if anyone could help me make this code I wrote better and a bit more readable and shorter. I have 8 images on the home page so the php code is like this: Code: [Select] <?php $images = array('image1', '8', 'image2', 'image7', 'image5', 'image4', '9', 'image6'); $i = rand(0, count($images)-1); $selectedImage1 = "_images/showreel/{$images[$i]}.jpg"; ?> <?php $images = array('image1', '8', 'image2', 'image7', 'image5', 'image4', '9', 'image6'); $i = rand(0, count($images)-1); $selectedImage2 = "_images/showreel/{$images[$i]}.jpg"; ?> <?php $images = array('image1', '8', 'image2', 'image7', 'image5', 'image4', '9', 'image6'); $i = rand(0, count($images)-1); $selectedImage3 = "_images/showreel/{$images[$i]}.jpg"; ?> <?php $images = array('image1', '8', 'image2', 'image7', 'image5', 'image4', '9', 'image6'); $i = rand(0, count($images)-1); $selectedImage4 = "_images/showreel/{$images[$i]}.jpg"; ?> <?php $images = array('image1', '8', 'image2', 'image7', 'image5', 'image4', '9', 'image6'); $i = rand(0, count($images)-1); $selectedImage5 = "_images/showreel/{$images[$i]}.jpg"; ?> <?php $images = array('image1', '8', 'image2', 'image7', 'image5', 'image4', '9', 'image6'); $i = rand(0, count($images)-1); $selectedImage6 = "_images/showreel/{$images[$i]}.jpg"; ?> <?php $images = array('image1', '8', 'image2', 'image7', 'image5', 'image4', '9', 'image6'); $i = rand(0, count($images)-1); $selectedImage7 = "_images/showreel/{$images[$i]}.jpg"; ?> <?php $images = array('image1', '8', 'image2', 'image7', 'image5', 'image4', '9', 'image6'); $i = rand(0, count($images)-1); $selectedImage8 = "_images/showreel/{$images[$i]}.jpg"; ?> And the HTML is like this: Code: [Select] <div id="slider1" class="nivoSlider"> <img src="<?php echo $selectedImage1; ?>" alt="John Richard Cleckheaton West Yorkshire" /> <img src="<?php echo $selectedImage2; ?>" alt="John Richard Cleckheaton West Yorkshire" /> <img src="<?php echo $selectedImage3; ?>" alt="John Richard Cleckheaton West Yorkshire" /> <img src="<?php echo $selectedImage4; ?>" alt="John Richard Cleckheaton West Yorkshire" /> <img src="<?php echo $selectedImage5; ?>" alt="John Richard Cleckheaton West Yorkshire" /> <img src="<?php echo $selectedImage6; ?>" alt="John Richard Cleckheaton West Yorkshire" /> <img src="<?php echo $selectedImage7; ?>" alt="John Richard Cleckheaton West Yorkshire" /> <img src="<?php echo $selectedImage8; ?>" alt="John Richard Cleckheaton West Yorkshire" /> </div> I no this code is terrible but I am still learning. Just a few months ago I had never touched PHP. Any help would be greatly appreciated. Regards Barry This is going to be tricky for everyone but here is goes. I have a random image function however I want the image attatched to a link that will go to the person's bio page. Even if I query anything how can I make sure that it matches up with what the right link person. <a href="bio/".$shortname.""><img src="images/spotlight/<?php randlogo(); ?>" alt=".::Spotlight A KOW Superstar::." /></a> <?php function randlogo(){ $img = array(); if($handle = opendir('images/spotlight/')) { $count = 0; while (false !== ($file = readdir($handle))) { if(strlen($file) > 2){ $img[$count] = $file; $count++; } } } echo $img[rand(0, (count($img)-1))]; } ?> Hey guys, i've made a script to display a random image. Works perfect on firefox, ie but not chrome =/. Rotate.php <?php // rotate images randomly but w/o dups on same page - format: // <img src='rotate.php?i=0'> - rotate image #0 - use 'i=1' // for second, etc // (c) 2004 David Pankhurst - use freely, but please leave in my credit $images=array( // list of files to rotate - add as needed "images/1.jpg", "images/2.jpg", "images/3.jpg", "images/4.jpg", "images/5.jpg", "images/6.jpg", "images/7.jpg", "images/8.jpg", "images/9.jpg" ); $total=count($images); $secondsFixed=2; // seconds to keep list the same $seedValue=(int)(time()/$secondsFixed); srand($seedValue); for ($i=0;$i<$total;++$i) // shuffle list 'randomly' { $r=rand(0,$total-1); $temp =$images[$i]; $images[$i]=$images[$r]; $images[$r]=$temp; } $index=(int)($_GET['i']); // image index passed in $i=$index%$total; // make sure index always in bounds $file=$images[$i]; header ("Location: $file"); header ("Content-Length: 0"); exit; ?> and then to call it, script.php <img src='rotate.php?i=0' width="90%" height="90%" alt="" /> Hi all, I have an issue with an image upload script. So far the script will upload the image to the server and rename it with a random 5 digit number on the end. I then INSERT this data into a table for sourcing the image later on. the only problem is that the data in the table is the image's original name not the new one. how do I get it to change that name too? Thanks. Code: [Select] <?php $idir = "uploads/"; // Path To Images Directory if (isset ($_FILES['fupload'])){ //upload the image to tmp directory $url = $_FILES['fupload']['name']; // Set $url To Equal The Filename For Later Use if ($_FILES['fupload']['type'] == "image/jpg" || $_FILES['fupload']['type'] == "image/jpeg" || $_FILES['fupload']['type'] == "image/pjpeg") { $file_ext = strrchr($_FILES['fupload']['name'], '.'); // Get The File Extention In The Format Of , For Instance, .jpg, .gif or .php $copy = copy($_FILES['fupload']['tmp_name'], $idir. basename($_FILES['fupload']['name'], $file_ext).rand(10000 , 99999).$file_ext); // Move Image From Temporary Location To Perm } } error_reporting (E_ALL ^ E_NOTICE); $usr = "user"; $pwd = "pword"; $db = "db"; $host = "host"; # connect to database $cid = mysql_connect($host,$usr,$pwd); if (!$cid) { echo("ERROR: " . mysql_error() . "\n"); } if ($_POST['submit']) { $logo = mysql_real_escape_string("$idir" . $_FILES['fupload']['name']); $SQL = " INSERT INTO mhhire "; $SQL .= " (logo) VALUES "; $SQL .= " ('$logo') "; $result = mysql_db_query($db,$SQL,$cid); $last=mysql_insert_id(); if (!$result) { echo("ERROR: " . mysql_error() . "\n$SQL\n"); } header("location:thanks.php"); exit(); } ?> I have a very simple piece of code to create a grid based gallery. The thumbnails are loaded from a single directory and are name 1.jpg... 2.jpg... 3.jpg etc At the moment the images appear to be loaded in randomly. I want them to load in numerically in terms of their filename. I know I may need to use 'sort' or 'natsort' but where in the code? Thanks for any help you can give me Code: [Select] <? $images = "Images/Bag Thumbs/"; # Location of small versions $big = "ruxxwomens.php?id="; # Location of big versions (assumed to be a subdir of above) $cols = 4; # Number of columns to display if ($handle = opendir($images)) { while (false !== ($file = readdir($handle))) { if ($file != "." && $file != ".." && $file != rtrim($big,"/")) { $files[] = $file; } } closedir($handle); } $colCtr = 0; echo '<table width="800" cellspacing="0" cellpadding="0" border="0"><tr>'; foreach($files as $file) { if($colCtr %$cols == 0) echo '</tr><tr>'; echo '<td align="center"><a href="' . $big . $file . '"><img src="' . $images . $file . '" cellspacing="0" cellpadding="0" border="0"></a></td>'; $colCtr++; } echo '</table>' . "\r\n"; ?> My images generator comprises
an array of image names extracted form an images table from a database using a select statement
a random number generator,
and a string that builds the correct pathname for the selected file.
To select one of the images for display, i generate a random number between 1 and the length of the array.
Though the generator is working, I noticed one of the random numbers is throwing up this error:
Warning: getimagesize(images/): failed to open stream: No such file or directory in
An inspection of the array reveals 2 array elements (representing my number of images) but one array element is NULL ( the first entry in the banner table
image_generator.php
require_once('connection.inc.php'); $sql = 'SELECT `filename` FROM banner'; $result = $mysqli->query($sql, MYSQLI_STORE_RESULT) or die(mysqli_error()); $row = $result->fetch_array(MYSQLI_ASSOC);//an array of image names $count = $result->num_rows; for ($i = 1; $i <= $count; ++$i) { $row[$i] = $result->fetch_array(MYSQLI_ASSOC); } $i = rand(1, $count); //a random number generator, //The random number is used in the final line to build the correct pathname for the selected file. $selectedImage = "images/{$row[$i]['filename']}"; if (file_exists($selectedImage) && is_readable($selectedImage)) { $imageSize = getimagesize($selectedImage); }var_dump($row) array (size=1) 'filename' => string 'ginsomin2.jpg' (length=13) nullRANDON IMAGE DISPLAY require_once 'image_generator.php'; <div id="banner" class="wrapper clearfix"> <img src="<?php echo $selectedImage; ?>" alt="banner"> </div>Kindly advice how i may proceed from here? Thanks. As above, I have a lottery style site that picks a random number between 1-8 but my users complain for some reason that this is not enough. So i was told to look into using fopen and random.org to generate a random number. Anyone have experience of this and perhaps a code snippet for me to look at and possibly use? help will be appreciated. I'm attempting to set up a script that will choose a "random" image from a directory and then place it in an article when it's posted. I currently have a php file that randomly assigns a picture on each refresh, however my employer wants the image to be static after posting. So I guess the short of my question is, what would be the best way to go about something like that or is it even doable with PhP. I know this is not coding.. However... How tolerant is PHP from generating a random output from 1000s of entry columns in a mysql database. I would like to make a script that would potentially pick one of a 1000 results at random. is this a problem with being ran multiple times? Wow, I have no clue what I'm doing.. I'm trying to make a random game and if you roll a 6, you will win 500 rp and I'm trying to insert the 500 rp into the user who is logged in ($_SESSION['username'). But I... just don't know where to begin. Here is my crappy coding that I just.. am stumped on: <p><?php $dice = rand(1,6); if($dice == 1){ echo "You rolled a <br><b>1</b>"; }if($dice == 2){ echo "You rolled a <br><b>2</b>"; }if($dice == 3){ echo "You rolled a <br><b>3</b>"; }if($dice == 4){ echo "You rolled a <br><b>4</b>"; }if($dice == 5){ echo "You rolled a <br><b>5</b>"; }if($dice == 6){ echo "You rolled a <br><b>6</b>"; } $winner = "500"; if($dice == 6); { include("haha.php"); $cxn = mysqli_connect($dbhost,$dbuser,$dbpassword,$dbdatabase); $sql = "INSERT INTO Member (rp) VALUES ('$winner')"; mysqli_query($cxn,$sql); } ?> is there a way to make a random number input into mysql? like if i add a new customer to a table, i want to assign a random number to that customer. Is there anyway in MySQL you can select a random record in a table? I normally do this by generating a random number first and then using that number to find a record but was wondering if there is an easier way. Thanks for any help. Hi, I want to pick out a random letter from a to h. How can I do this? So everytime the page re-loads, a random letter (range a-h) will show. Thanks alot for any help. Im trying to figure out the best way to random a line from a text file and after the random delete that line from the file. This way the same username cannot be picked twice thanks for any input I want to loop through all the values of an array.. but each time, JUST FOR THE LOOP, i want to go through the array values randomly. How do you suggest I do this? How would I make it so that for every set of data where a fieldname is 1+ it picks a random one out. For example User Hit Luke 0 Peter 1 Alex 3 Peter 1 For every value where Hit is 1 or over it selects out of the query results a random username. I dont know how to word this really. what I want to do is Code: [Select] $Var[] = 3; $Var[] = 6; $Var[] = 2; $Var[] = 17; for($i=0; $i!=count($Var); $i++) { echo "#$i: ".$Var[$i]."\n"; } I know I might be able to use rand() but I need it to echo ALL of the variables in the array in a random order, I know if I use count to find out how many variables there are that it would echo them 4 times randomly but might echo the same variable 2 times making it to where it only echos 3 different varables, if I am being confusing please let me know, I just want to get this resolved, thanks! hello, i am trying to see how i can pick a random number between 1-15 and exclude certain numbers. so i have a staff list that once a random number is created it inserts it into the staffnumber field. so the next time i create a random number for a staff, i want to make sure that the random number doesnt select an existing staffnumber. thanks! how do I pull out two random integers at the same time without ever possibly choosing the same integer twice? |