PHP - Random Number
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! 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. 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. 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? 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! I need to choose a random number that doesn't currently exist in the database Hi all, sorry cos there is no code. please how can i generate pairs (in twos, threes, fours or five) from a given set of numbers. the numbers are to be typed in the form text field and when click generate(submit button) it brings out the pair of numbers. thanks in advance my form Code: [Select] <form id="form1" name="form1" method="post" action=""> <table width="100%" border="0" cellspacing="2" cellpadding="1"> <tr> <td width="21%">Input Numbers : </td> <td width="79%"><input name="numbers" type="text" id="numbers" size="50" /></td> </tr> <tr> <td> </td> <td><input name="generate" type="submit" id="generate" value="Generate" /></td> </tr> <tr> <td colspan="2"> </td> </tr> <tr> <td colspan="2"> </td> </tr> <tr> <td colspan="2"> </td> </tr> <tr> <td colspan="2"> </td> </tr> </table> </form> Hello, I am trying to create a simple game random number guessing game in PHP. Currently, I have an HTML page with a form on it where the user enters a number. Then when the user clicks the submit button on the form, their number is passed onto the second page. On the second page, I have some PHP code that generates a random number between 1 and 20, then it checks to see if the two numbers are the same. If they are the same, it says correct. If the guess is higher, it says so. If the guess is lower, it says so. I also made it display a form to re-guess the number (if the initial guess was incorrect). The problem I have is when the user attempts to re-guess the number. Whenever the user attempts to enter a new guess, the random number changes. I want to make it so that the random number stays the same as it is. Any help? Here is the Code for the first HTML page: Code: [Select] <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" /> <title>phpNumberGame</title> <link href="style.css" rel="stylesheet" type="text/css" /> </head> <body> <div id="main"></div> <div id="enterNumber"> <form action="result.php" method="post"> Enter a number: <input type="text" name="inputnumber" /><br /> <input type="submit" value="Guess" /> </form> </div> </body> </html> Here is the code for the second page: Code: [Select] <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>result</title> <link href="style.css" rel="stylesheet" type="text/css" /> </head> <body> <div id="main"></div> <div id="enterNumber"> <?php $number_actual = rand (1,20); $number_guess = $_REQUEST["inputnumber"]; echo "You chose: " . $number_guess . "<br />"; echo "The random number is: " . $number_actual . "<br />"; if ($number_guess==$number_actual) echo "You guessed <b>Correctly!</b>"; elseif ($number_guess<$number_actual) { echo "You are too <b>Low</b>!"; echo "<br />"; echo "<br />"; echo "Try guessing again..."; echo "<form> <input type='text' name='inputnumber' /> <input type='submit' value='Guess' /> </form>"; } elseif ($number_guess>$number_actual) { echo "You are too <b>High</b>!"; echo "<br />"; echo "<br />"; echo "Try guessing again..."; echo "<form> <input type='text' name='inputnumber' /> <input type='submit' value='Guess' /> </form>"; } ?> </div> </body> </html> Here is what I have so far on my website, you can see it he http://joshkautz.com/phpNumberGame/phpNumberGame.html I think I included everything necessary for people to give input, if not please let me know and I will give more information! Do I need to redo things completely? Any advice would be greatly appreciated. Thanks a ton! I'm hoping someone can show me how to get a random decimal number. I've googled and can't find anything that works. I need to find a random number between 1.0 and 10.0 I can get a random whole number no problem, but decimals aren't working. When I finally get that working, ideally I'd like to be able to find a random number between two decimals (like above) but also have a small chance of getting a decimal slightly higher than the two given. So, for example, maybe a random decimal between 3.5 and 6.0, but a slight chance of getting 6.2? Thank you very much for any help! I have 3 columns in my DB: email (primary), unique_code, timestamp Users enter their email address and it is added to the DB, including an alphanumeric 5 digit unique code in the 'unique_code' column and a timestamp in the 'timestamp' column. 1. The email address is being added, but not the unique code? What is the issue here and what can I should I specifically do to fix it? 2. The next thing is that I need to display that code to the user in where it says <?php echo $unique_code;?>. How can I do that? DB is as follows: Field Type Collation Attributes Null Default Extra Action email varchar(64) utf8_unicode_ci No None unique_code varchar(64) utf8_unicode_ci No None timestamp timestamp on update CURRENT_TIMESTAMP No CURRENT_TIMESTAMP INDEXES PRIMARY BTREE Yes No email 7 A Full code Code: [Select] <?php require "includes/connect.php"; $msg = ''; if($_POST['email']){ // Requested with AJAX: $ajax = ($_SERVER['HTTP_X_REQUESTED_WITH'] == 'XMLHttpRequest'); try{ if(!filter_input(INPUT_POST,'email',FILTER_VALIDATE_EMAIL)){ throw new Exception('Invalid Email!'); } $mysqli->query("INSERT INTO coming_soon_emails SET email='".$mysqli->real_escape_string($_POST['email'])."'"); if($mysqli->affected_rows != 1){ throw new Exception('This email already exists in the database.'); } if($ajax){ die('{"status":1}'); } $msg = "Thank you!"; $mysqli->query("INSERT INTO coming_soon_emails VALUES('email', SUBSTRING(MD5(UUID()),FLOOR(RAND()*25),5), UNIX_TIMESTAMP())"); echo "Something went wrong:" . $mysqli->error; } catch (Exception $e){ if($ajax){ die(json_encode(array('error'=>$e->getMessage()))); } $msg = $e->getMessage(); } } ?> <!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>example</title> <link rel="stylesheet" type="text/css" href="css/styles.css" /> </head> <body> <div id="container"> <form id="form" method="post" action=""> <input type="text" id="email" name="email" value="<?php echo $msg?>" /> <input type="submit" value="Submit" id="submitButton" /> </form> <div id="thankyou"> Thank you! <?php echo $unique_code;?></p> </div> </div> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.3/jquery.min.js"></script> <script src="js/script.js"></script> </body> </html> Thank you! This isn't for anything practical, I'm just fiddling. Anyways, I'm wondering if there's anyway to make this more efficient since at higher lengths it could become really heavy. $l is length of the number. function fixed_random($l) { $number = ""; do { $r = mt_rand(0, $l); $number .= $r; } while (strlen($number) < $l); return $number; } Can someone help me create this?? Upon outside entry, a random number is chosen between 1 and 10. Use this function to generate the guess number $guessnum = rand(1,10); // you may change the variable name The user tries to guess this number by choosing from a selection list of possibilities. The user "loses" if there are three failed attempts. For reentrant activations the selection list must be sticky and the same guess number must be maintained. The guess number and the attempt number must both be propagated through hidden inputs. Here is a screen shot: Upon outside entry, or using the "Start Over" hyperlink (with the list activated): Let's suppose the number to be guessed is 6. I select 4 and guess it. Response should say "Try #1" I select 9 and guess it. Response should say "Try #2" I select 3 and guess it. Response should say "You Lose" At this point assume that we must "Start Over". This time, suppose the generated number is 8. I select 8 and guess it. Response should say "You Win" Again, assume we must "Start Over". I am trying to make a function that will generate a random number letter combo but the letters can only be abcde, no others. It must come out in the format, 1a~3d~9b~ etc. This is what I have so far: Code: [Select] function randomNumLet($amount){ $theNos = array('1', '2', '3', '4', '5', '6', '7', '8', '9'); $theLet = array('a', 'b', 'c', 'd', 'e'); $combo = ''; for($i=0;$i<$amount;++$i) { $rand_num = array_rand($theNos, 1); $rand_let = array_rand($theLet, 1); $combo .= $theNos[$rand_num[0]].$theLet[$rand_let[0]].'~'; } return $combo; } $num_let = randomNumLet(2); echo $num_let; And it returns just '~~' with no numbers or letters. I'm a bit stuck here and would appreciate any help. How can I make the function output 1a~4d~ etc? Cheers, Joe I'm looking for a random number generator, that chooses a number every hour, and when it does it will be out of 100 (these are player ID's) once the number is chosen, I would like 10 Crystals (special payment) to be given to the number (ID). Is this possible and if so, please help. This is all I have (generator) function createRandomAGTNO() { do { $agt_no = mt_rand(1,100); $valid = true; if (preg_match('/(\d)\1\1/', $agt_no)) $valid = false; // Same digit three times consecutively elseif (preg_match('/(\d).*?\1.*?\1.*?\1/', $agt_no)) $valid = false; // Same digit four times in string } while ($valid === false); return $agt_no; } Please reply ASAP? Hello, I'm currently creating a little script, and want to assign a random number to a row in the MySQL table as soon as it will be inserted. But that number may not have been used before. How will I do this? I tried if else thingies, but then the code would be very long (just in case it randomly picks 10 times after each other a number that exists). $randomnumber = rand(10000000, 99999999); if(mysql_num_rows(mysql_query("SELECT * FROM table WHERE randomnumber='".$randomnumber."')) == 1) { $randomnumber = rand(10000000, 99999999); if(mysql_num_rows(mysql_query("SELECT * FROM table WHERE randomnumber='".$randomnumber."')) == 1) { $randomnumber = rand(10000000, 99999999); }else { // Insert into database } }else { // Insert into database } I hope you understand my problem. Regards, Is it possible to remember the last created random number with PHP or do I need to make use of MySQL? I want to generate an equation with submit button 1 and echo it out, and then I want the script to calculate the printed out equation with submit button 2. The problem: As soon as I click submit button 2, the numbers change into different random numbers, since the PHP starts scanning from the top of the file again as soon as the second button has been pressed. $gen = $_POST['gen']; $calc = $_POST['calc']; $x1 = random_number (); $x2 = random_number (); $op = random_op (); echo " <form action='' method='POST'> <input type='submit' name='gen' value='Generate' /><br /> <input type='submit' name='calc' value='Calculate' /> </form> "; if ($gen) { echo "$x1 $op $x2 = ? <br /><br />"; } if ($calc) { switch ($op) { case '+' : $row_1 = $x1 + $x2; break; case '-' : $row_1 = $x1 - $x2; break; case '*' : $row_1 = $x1 * $x2; break; case '/' : $row_1 = $x1 / $x2; break; } echo "$x1 $op $x2 = $row_1"; } I could of course insert the generated numbers into the database and fetch it out again, but I was wondering if it's possible to remember the numbers (even when the 2nd submit buttons has been pressed) within PHP as well? thanks. How to generate a unique random number in php??? Any one who can help me? Hello, I am using the following code to display images managed by a MySQL database. Basically another program manages a bunch of images, but this script displays certain ones (ones with INCLUDE = 1 in the database) on my main page. My question is, is there an easy way to limit the number of images it displays, say to 5? I'm not too concerned which images actually display (ascending or descending)... or better yet, random! Most importantly, I only want five to display. Each image will be linked to the full page, which displays all the images. Any ideas? Thanks! Code: [Select] <?php $username="XXXXXXX"; $password="XXXXXXX"; $database="XXXXXXX"; mysql_connect(localhost,$username,$password); @mysql_select_db($database) or die( "Unable to select database"); $query="SELECT * FROM ft_form_12 WHERE col_24='1'"; // $query="SELECT * FROM ft_form_12"; // SELECT * FROM ft_form_12 WHERE col_24='1' $result=mysql_query($query); $num=mysql_numrows($result); mysql_close(); ?> <?php $i=0; while ($i < $num) { $f20=mysql_result($result,$i,"col_23"); //Photo file name $f21=mysql_result($result,$i,"col_24"); //INCLUDE ?> <a href="http://www.domain.com/display_whole_page.shtml"><img src="http://www.domain.com/the_file/pictures/<?php echo $f20; ?>" height="50" border="0"></a> <?php $i++; } ?> Hello I've got a php script that generates random number every page refresh Code: [Select] <?php srand ((double) microtime( )*1000000); $random_number = rand(1000,5000); echo "$random_number"; ?> I would like some advanced things... first of all i don't want the random number to be generated every page refresh I would like something like... based on pc hour example: - between 12 AM and 5 AM it will generate a number from 500 to 1000 randomly but the number should change also to a determined time i set such as every 5 minutes and not everytime i refresh the website page - betweem 5 AM - 2 PM will generate a number from 3500 to 8000 and this number will change every 5 minutes too with one that exists between this interval - and so on Would appreciate if someone could help me with that Thanks in advance I am looking to generate a random number for every user contribution as a title of the contribution. I could simply check the database each time with a query and generate a number which does not equal to any of the entries of the database. But I imagine this as inefficient and it could become slow if the database is big in my opinion. Also I'd have to contain all the numbers of the database somewhere to manage the "not equals to", in an array or something similar but that can end up as a giant one. Excuse the layman's speech I am new to this. Any suggestions how this can be solved efficiently without straining the resources too much? You can explain it linguistically and do not have to provide me any scripts, I will figure it out. This might be a bit hard to explain! I have a grid, 32x32 which is actually 1024 mySQL rows in a table, you can see the table he http://interbitlotto.com/grid each cell is a row in the database, top left is ID 1, bottom right is id 1024. get it? right well its a battle ship game, and im stuck on the automatic battle ship placement script. I have displayed the generated boats as misses so we can see them. The problem i am having, is that the random number generater chooses a cell too close to the side so the boat ends up wrapping to the other side. I cant think of a way to detect if its going to wrap, if it is then choose another cell... The code below chooses the orientation of the boat, then chooses a random cell... but as you can see, no code for "across" to stop it choosing one too close to the side. Any ideas? Code: [Select] $orientation = rand(1,2); //get random orientation - 1 = down, 2 = across. if ($orientation == 1){ $multiply = 32; //cells till next row $max = 1024 - (32 * $boatlength); //prevents it from choosing a cell too close to the bottom $startcell = rand(1,$max); }else{ $multiply = 1; //across, so next cell $max = 1024; $startcell = rand(1,$max); } |