PHP - Php Shuffle/random
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. Similar TutorialsI get strings via simplexml with this code $xml = simplexml_load_file("test.xml"); foreach ($xml->title->case as $value){ $param1 = $value->param1; $param2 = $value->param2; Now I want to randomize the xml items (not in their original order); but I cannot use shuffle($value); because it does not consider $value as an array. How can I make a random order? Ok I'm really lost here, what I need to do is shuffle a 2D array. Now when I shuffle them I want to keep both columns aligned to say. Like I only want the index to change. Kinda like this: Index Id URL 0 [2 www.e] I want the bracketed stuff to stay aligned. 1 [6 www.b] 2 [12 www.c] 3 [60 www.h] But I want them in different positions on every page load. So when I echo array[1][0] it will always be different. Is this even possible? I'm creating a quick survey app for my son's cub scout pack's end-of-year surveys. There are two sets of questions: those where they want the responses to be completely anonymous and those questions where we need to know who filled out the response (people volunteering for positions, etc) I'm storing the responses in the db as two separate arrays, $anon and $nonAnon $anon[0] will be an array containing all the questions: $anon[0][0] = Survey question # 1 $anon[0][1] = Survey question #2, etc. The responses will be stored as arrays and placed in $anon as the 2nd element: $anon[1][0][0] = first response, answer to the first question $anon[1][0][1] = first resopnse, answer to the 2nd question $anon[1][1][0] = 2nd response, answer to the 1st question Etc. The pack leadership is concerned that no one would be able to reconstruct which anon response belonged to whom by matching up the order of the anon answers with the non-anon answers. Therefore I'd like to shuffle at least the anon responses. The long answer would be to build a temp array using the elements in $anon[1] and then shuffle that array and then reassign it to $anon[1]. Is there a way to use shuffle directly on $anon[1] without having to build a temporary array, shuffling it, then replacing the elements of $anon[1]? 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 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? 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 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' ")); ?> 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.... 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 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? 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 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. 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! 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))]; } 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 All I am using the below code to display users registered on my site: Code: [Select] <div class="profilbox" id="apDiv11"><div></div> <div align="center">Registered Users</div> <div class="text_area"><?php //to display image from source - registerd users $dir = "profpics"; echo '<table>'; $result = mysql_query("SELECT * FROM users order by id"); while ($row = mysql_fetch_assoc($result)) { echo "<tr><td><img src=\"$dir/{$row['prof_pic']}\" width='40' height='40'>{$row['username']}</td></tr>"; } //close out table echo '</table>'; ?></div> </div> Could anybody tell me how i can limit this to 3 random results? I then plan adding a link to 'see all' 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: i wanted to choose 5 random numbers from 0-20. each number represents an index in an array. is there a way to pick out 5 random items from the array. say if random number generator piked a number 22, the last item in the array is at index 20, it wud then have to go to index 0. thanks! 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 = ""; } ?> |