PHP - Php Random
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? Similar TutorialsAs 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. here is the database: its a facebook app i want that my sql will choose every time random but considerate in the sex parameter. i mean that if the user is boy i will put it in parameter and boys is num-1 girls-0 and if the user is boy it will run random sql just on the boys and if its girls so random on the girls here what i did: $sql = "SELECT * FROM pcm ORDER BY RAND() LIMIT 1"; $Recordset3 = mysql_query($sql) or die(mysql_error()); $row2 = mysql_fetch_object($Recordset3); print_r($row2); but for some reason i get an error that the database is not selected maybe i didnt select my database right? please help tnx.... 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))]; } 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); } ?> Hi Guys, I have a php script to upload a photo to a mysql table. This works great, until someone uploads a file with the same name, then it replaces the old one. Bad times! So Ive researched it and I have put a timestamp on the filename and it uploads with the correct timestamp in the images folder. However the data that it uploads to the table is just the original filename, ie it doesnt stamp the filename in the table therefore they dont match... Any ideas... <?php include('config.php'); if (isset($_GET['Ter']) ) { $ter = (int) $_GET['Ter']; if (isset($_POST['submitted'])) { //Photo Upload //This is the directory where images will be saved $name=time(); $target = "images/"; $target = $target .$name. basename( $_FILES['photo']['name']); //This gets all the other information from the form $photo = ($_FILES['photo']['name']); //Pause Photo Upload foreach($_POST AS $key => $value) { $_POST[$key] = mysql_real_escape_string($value); } $sql= "UPDATE `ter` SET `Ter` = '{$_POST['Ter']}' , `BranchName` = '{$_POST['BranchName']}' , `BranchAddress` = '{$_POST['BranchAddress']}' , `BranchTel` = '{$_POST['BranchTel']}' , `BranchEmail` = '{$_POST['BranchEmail']}' , `BranchLink` = '{$_POST['BranchLink']}' , `Theme` = '{$_POST['Theme']}' , `LocalInfo` = '{$_POST['LocalInfo']}' , `BranchInfo` = '{$_POST['BranchInfo']}' , `photo` = '{$_FILES['photo']['name']}' WHERE `Ter` = '$ter' "; mysql_query($sql) or die(mysql_error()); //Unpause Photo Upload //Writes the photo to the server if(move_uploaded_file($_FILES['photo']['tmp_name'], $target)) { //Tells you if its all ok echo "<br />The file ". basename( $_FILES['photo']['name']). " has been uploaded. <br />"; } else { //Gives and error if its not echo ""; } //End of Photo Upload echo (mysql_affected_rows()) ? "<br />Edited Branch.<br />" : "<br />Nothing changed. <br />"; } $row = mysql_fetch_array ( mysql_query("SELECT * FROM `ter` WHERE `Ter` = '$ter' ")); ?> 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? Hi Guys I have a code what inserts very simple queries to database, im trying to add a random reference number for each enrty using $reference = rand(111111111111,999999999999); but each time I add an entry it gives me the same random number previously generated for previous entry can you help pleasE? 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. 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))]; } ?> 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. Okay, minor issue, but not sure how to resolve. I have a form that processes through PHP and has it's fields validated with JS and sends the data to an e-mail address and a database. It works fine, but there are random times where a submitted entry will show up blank in the e-mail and not be in the database at all, any ideas on what might be causing this? Thanks. Alright, I have a random thing going on. Works perfectly fine. This is the code: Code: [Select] <?php include("config.php"); //To change the odds, change the second number in the rand() function. $rand = floor(rand(0,1)); if($rand == 1) { $sql = "SELECT * FROM randomevents WHERE rarity <= '10'"; $result = mysqli_query($cxn, $sql); while ($row = mysqli_fetch_assoc($result)) { $event[] = $row['phrase']; if ($row['type'] == 'gainsp') { $rand = rand(200,500); $sql = "UPDATE members SET starpoints = starpoints+$rand WHERE userid='".$_SESSION['userid']."'"; mysqli_query($cxn, $sql) or die("Query died: updating starpoints"); } } //This will pick a random event and show it $renum = floor(rand(0,count($event))); $eventdisplay = $event[$renum]; } ?> In the database, I have the phrases set as: "You have gained {$rand} starpoints!". How do you make that variable echo out as the $rand I'm generating on this page? It just keeps posting as is. When I went the {$rand} to display as the number I'm generating to set their starpoints to. So I guess how do you hold a variable in the database? Does anyone understand what I'm asking? Here as an image to help understand: Hi, I'm having trouble generating random string with 8 characters, when I refresh I sometimes get 6 characters and sometimes 8. "-" not included as character. Wrong: 6JW-F7W Correct: (should always generate random like this) DVMF-F36V I know I'm trying to achieve this in wrong methods but it's the only way I know. Hope someone can help. function getReference() { $length = 8; $characters = "0123456789abcdefghijklmnopqrstuvwxyz"; for ($p = 0; $p < $length; $p++) { $string .= $characters[mt_rand(0, strlen($characters))]; } return strtoupper(substr($string, 0, -$length/2)."-".substr($string, $length/2-1, -1)); } Hi Guys I need some help this is my first real php website. Im trying to retrieve results from an accommodation database, to make the results fair I need to return a random set of results so each accommodation get a fair viewing and nobody is always at the bottom. The problem arises when i paginate the results, because each page executes a separate randomly ordered offset mysql query I can end up showing the some of the same results over and over on multiple pages. This is going to confuse and irritate searchers. How can i achieve results and paginate them where each accommodation gets a fair chance at the first page each time the database is searched? 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 Im 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 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. It's working great, but at some points after one of the random events goes through, I reload the page and it either gives me or takes away some starpoints without showing the message.. but it shows the message all the other times. Could someone help me debug this and see why it's doing that? Code: [Select] <?php include("config.php"); //To change the odds, change the second number in the rand() function. $rand = rand(1,3); if($rand == 1) { $sql = "SELECT * FROM randomevents WHERE rarity <= '10'"; $result = mysqli_query($cxn, $sql); //Write the events in here with the opener: $event[] = "#your event#"; while ($row = mysqli_fetch_assoc($result)) { $event[] = $row['phrase']; } //This will pick a random event and show it $renum = rand(0,count($event)); $display = $event[$renum]; if ($display == "") { $eventdisplay = ""; } else { $eventdisplay = "<table cellspacing=\"0\" class=\"events\" align=\"center\"><br> <tr><br> <td><center><b><h1>Random Event</h1></b></center></td><br> </tr><br> <tr><br> <td><img src=\"".$_SERVER['SCRIPT_NAME']."\"> <p><center>".$display."</center></p><br> </td><br> </table><br>"; $sql = "SELECT type FROM randomevents WHERE phrase='".$display."'"; $result = mysqli_query($cxn, $sql); $row = mysqli_fetch_assoc($result); if ($row['type'] == "gainsp") { $rand = rand(200,500); $sql = "UPDATE members SET starpoints = starpoints+$rand WHERE userid='".$_SESSION['userid']."'"; mysqli_query($cxn, $sql) or die("Query died: updating starpoints"); } elseif ($row['type'] == "losesp") { $rand = rand(50,100); $sql = "UPDATE members SET starpoints = starpoints-$rand WHERE userid='".$_SESSION['userid']."'"; mysqli_query($cxn, $sql) or die("Query died: updating starpoints"); } else {} } } else { $eventdisplay = ""; } ?> I'm just searching for some input on a function I saw and wanted someone who could explain to me what this function would mean. As I have the same db structure and was curious specifically to know what sort of values I should have inside of the fields for varcharfield and textfield. function customfieldinput($fedid,$id,$groupid,$styleid) { $query = "SELECT field.id as getfieldid, field.is_custom as getiscustom, field.fullname as getfullname, customfields.id as getcustomfieldid, customfields.varcharfield as getvarchar, customfields.textfield as gettext FROM efed_list_fields as field LEFT JOIN efed_content_customfields as customfields ON ( field.id = customfields.field_id and customfields.character_id = '$id' ) WHERE field.fed_id = '$fedid' and field.style_id = '$styleid' and field.group_id = '$groupid' and field.enabled = '1' and field.is_custom > '0' ORDER BY field.is_custom,field.fullname"; $result = mysql_query ($query); while ($row = mysql_fetch_assoc($result)) { $fieldarray=array('getfieldid','getiscustom','getfullname','getvarchar','gettext','getcustomfieldid'); foreach ($fieldarray as $fieldlabel) { if (isset($row[$fieldlabel])) { $$fieldlabel=$row[$fieldlabel]; $$fieldlabel=cleanquerydata($$fieldlabel); } } if ((isset($getcustomfieldid)) && ($getcustomfieldid > "0")) { $update = "update"; } else { $update = "new"; } if ($getiscustom == "1") { print "<tr>\n"; print "<td width=120 class=rowheading>".$getfullname.":</td>"; print "<td class=row3><textarea name=\"custom".$getfieldid.$update."\" class=\"textarea490x100\">"; if ((isset($gettext)) && ($gettext != "")) { print $gettext; } print "</textarea></td>\n"; print "</tr>\n\n"; } else { print "<tr>\n"; print "<td width=120 class=rowheading>".$getfullname.":</td>"; print "<td class=row3><input type=text name=\"custom".$getfieldid.$update."\" class=fieldtext490"; if ((isset($getvarchar)) && ($getvarchar != "")) { print " value=\"".$getvarchar."\""; } print "></td>\n"; print "</tr>\n\n"; } if (isset($getcustomfieldid)) { unset ($getcustomfieldid); } if (isset($getvarchar)) { unset ($getvarchar); } if (isset($gettext)) { unset ($gettext); } } } |