PHP - 3 Random Numbers (no Duplication)
Hi
I have this simple code $one = rand(1,9); $two = rand(1,9); $three = rand(1,9); but I need to change it so that they are all unique and the same number is not used more than once can anyone help? thanks Similar TutorialsHello all, I am newbie to php programming, any suggestions or advance greatly appreciated. I can't figure out how to output two array random numbers in ascending order. <?php $l_numbers = array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47); $mega = range(1, 27); for($i = 0; $i <= 4; $i++) { $random1 = array_rand($l_numbers); echo "$random1 \n" ; } for($e = 1; $e <= 1; $e++) { $random2 = array_rand($mega); echo "<p> Mega number is $random2 </p>"; } echo "Winning numbers are $random1 and mega $random2"; ?> example: Winning numbers are 3,5,10,17,39 and mega 5. hi, I am trying to create 7 lines, out of 49 numbers, each line must have unique numbers not seen in any other line so that every number out of 49 has been used in one of those lines, I also need them to be in order, lowest to highest except for the last number which needs to be completely any random ( as long as its not elsewhere in the 7 lines and its one of 49) I have made an attempt, <?php function code(){ for ($i=1; $i<=7; $i++){ $one = mt_rand(1, 49); echo $one; echo ' '; }} function lines(){ for ($i=1; $i<=7; $i++){ code(); echo '<br/>'; }} lines(); ?> but I am seriously failing at producing every number from 1 to 49 throughout those 7 lines and of course failing at ordering them with the random at the end that is not in order.. sorry if this sounds confusing but I would appreciate any help, thanks Ello Everyone! Ok, well I'm making a script with a file uploading thingy, and well, I'm also using a random number to generate a number they must write on a paper and upload it. Issue: I'm experiencing a slight issue with the random numbers though. Once the user uploads their photo with the numbers, I'll send it to my MySQL database. When it gets to that point the random numbers changes, and the numbers will change. I can not find a way to keep it as is, without it changing until the numbers have been placed into the database. //Top part $array = array(); for($i = 0; $i<5; $i++){ $array[$i] = rand(0,20); } $randNum = implode($array); //HTML part <form method="post" action="" enctype="multipart/form-data"> <table> <tr> <td> Generated Number: </td> <td> <h2> <?php echo $randNum ?> </h2> </td> </tr> <tr> <td> Group Name: </td> <td> <input type="text" name="group" maxlength="15" /> </td> </tr> <tr> <td> Photo Taken: </td> <td> <input type="file" name="image"/> </td> </tr> <tr> <th colspan="2"> <input name="submit" type="submit" value="Register As An Artist"/> </th> </tr> </table> </form> //SQL Part if($copied){ $createArtist = mysql_query("INSERT INTO `artistregister` (user_id, groupname, photo, randomnum) VALUES ('".$_SESSION['id']."', '".$groupName."', '".$filePath."', '".$thisRandom."')"); $resetArtist = mysql_query("UPDATE `accounts` SET `isArtist` = '1' WHERE `user_id` = '{$_SESSION['id']}'"); if($createArtist){ if($resetArtist){ echo "Your account is now pending for Artist Access. This could take upto a week."; $_SESSION['isArtist'] = 1; } else{ echo "There was an error, and it had been recorded. Please try again later."; sendError(mysql_error(), $_SERVER['REQUEST_URI']); } } else{ echo "There was an error, and it had been recorded. Please try again later."; sendError(mysql_error(), $_SERVER['REQUEST_URI']); } } elseif(!$copied){ echo "There was an error, and it has been recorded. Please try again later."; sendError("Line 98", $_SERVER['REQUEST_URI']); } I've tried looking for different functions, and such, but I'm either not looking in the right place or I'm just making some stupid logical error. Thank you for looking. Hi there. I need a function that can generate 15 random numbers between (1,10) and then converts those numbers to Roman numbers. Anyone can help me? How do you generate a random number like say, 0 through 10? I want to select random sites from my database that have IDs 0 through 10. How would I compare 2 random numbers to rows in a table. The table has 4 rows and 2 colums. My table is setup like this: ID hp mp then has just randomly placed numbers from 0 to 5. So far my script looks like this: I have $new_hp=rand(0,5); $new_mp=rand(0,5). Then i query the db by $myquery=doquery("select hp,mp from users"; $myrow=mysql_fetch_array($myquery); once this is done would a while statement like while ($myrow = mysql_fetch_array($myquery) to what each line in the table has? I would then need to compare the random numbers to those entries in the database. Something like if($myrow[hp] == $new_hp && $myrow[mp] == $new_mp) { ? But if the if statement isnt true it needs go back choose another random number and run same again and again until the statement is true and that is where im stuck at so any help would be greatly appreciated Hello........ Currently i am struggling with php script....... can any one tell me or guide me how to code Automatically generating random number with in the range of 19 to 90 and the number has to change with in 24 hours time duration......... It's urgent........ Thanks in advance..... Rooban.S Hi, What I'm trying to do is create a script that generates a random list of cars whenever it is run. I have a list of available cars in a MySQL database. I'm just not sure how to get php to generate a list of, say, 20 cars, that are randomly picked from the cars in the database. I may also want to add other statistics like MPG (also already in the database). Can anyone show me how to do this? And is it possible to format the returned data in a table or div format? Thanks in advance Unk As part of an image gallery I am trying to INSERT data into a table to make accessible the relevant info of individual images - the problem I have encountered is that each query seems to be being inserted twice, and I can't figure out why. The code = Code: [Select] <?php /*============================================== Connect to MySQL and select the correct database ==============================================*/ mysql_connect("localhost", "uname", "pwd") or die(mysql_error()); echo "Connected to MySQL<br />"; mysql_select_db("gallery_db") or die(mysql_error()); echo "Connected to Database gallery_db.<br />"; /*============================================= Include the files needed to undertake this task =============================================*/ include("functions.php"); /*========================= Set up arrays and variables =========================*/ $store = array(); $exif = array(); $folder = "./images/"; $insrt = 'INSERT INTO images VALUES (img_id, '; $file_name = ''; $file_location =''; $copyright =''; $caption = ''; $file_date = ''; $file_time = ''; $camera = ''; $speed = ''; $fNo = ''; $ISO = ''; /*================================= Open folder and read relevant files =================================*/ if ($handle = opendir('./images')) { while (false !== ($file = readdir($handle))) { if ($file != "." && $file != "..") { $file_name = $file; //>>> File Name <<< $file_location = $folder . $file; //>>> File Location <<< $exif = exif_read_data($file_location, 'EXIF'); //>>> Read exif data <<< /*============================================================== Check if the 'Copyright' info existe in the exif data, and if it doesn't set the $copyright variable to the relevant value. ==============================================================*/ if (array_key_exists('Copyright', $exif)) { $copyright = $exif['Copyright']; } else { $copyright = "copy name"; } $caption = $exif['COMMENT'][0]; //>>> Get the Caption <<< //>>> Re-format DateTime into separate date and time var's $file_date & $file_time <<< $temp = substr($exif['DateTime'], 0, 10); $file_date = substr($temp, 8, 2) . substr($temp, 4, 4) . substr($temp, 0, 4); $file_time = substr($exif['DateTime'], 11, 8); //>>> Set the rest of the variables <<< $camera = $exif['Model']; //>>> Get the camera make and model <<< $speed = $exif['ExposureTime']; //>>> Get the shutter speed <<< $fNo = $exif['COMPUTED']['ApertureFNumber']; //>>> Get the f No. <<< $ISO = $exif['ISOSpeedRatings']; //>>> Get the ISO rating <<< //>>> Fill the $store[] array with the relevant bits for each seperate query <<< $store[] = $insrt . "'" . $file_name . "', " . "'" . $file_location . "', " . "'" . $copyright . "', " . "'" . $caption . "', " . "'" . $file_date . "', " . "'" . $file_time . "', " . "'" . $camera . "', " . "'" . $speed . "', " . "'" . $fNo . "', " . "'" . $ISO . "')"; } } closedir($handle); } /*============================================================================= Get individual queries from $store[] and INSERT INTO images the relevant VALUES =============================================================================*/ $num_queries = count($store); //>>> Check the number of queries in the array $store $loop = 0; //>>> Starting point for query No. bearing in mind that array keys are numbered from zero while ($loop <= $num_queries - 1) { $query = $store[$loop]; if (!mysql_query($query)){ die('Error: ' . mysql_error()); } mysql_query($query); $loop++; } ?> I know it's not pretty, but that can be attended to once working properly. I am quite sure that it will be a very simple solution, probably so simple that I haven't even thought of it. I've recently had a problem with my admin site where PHP sessions, which are stored in a MySQL database, are duplicating and causing the page to return to the login screen. Usually the site works fine in Firefox, but stops working in IE and Safari. This problem suddenly appeared over night with no change to the files. Due to the amount of code, I'm reluctant to post it all, but does anyone have a suggestion on why this could be happening and how to solve it? Hello there, I'm looking for a PHP method to duplicate a line, for example if I wanted to duplicate this line: mail($to,$subject,$message,$headers); How could I specify a value of how many are displayed instead of doing this to send it 3 times: mail($to,$subject,$message,$headers); mail($to,$subject,$message,$headers); mail($to,$subject,$message,$headers); Many thanks Hi
I am reading in data from a csv file
if (($handle = fopen("data.csv", "r")) !== FALSE) { while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) { echo "User Name: $data[0]"; echo "Booking IDs: $data[1]"; } echo "<hr>";The problem is some of the usernames are duplicated so get outputted the same user name 20 times but with different IDs, obviously but I am unsure how to group them together. I can't seem to figure out how to write if the next username is the same as current then just add another ID not go through the entire loop. Any ideas? Thanks <?php // Daniel URL duplicator. // Input links list. $linksList = "links.txt"; // How many times to duplicate the url? $manyTimes = 1000; // Read in the list. for ($x = 0; $x <= $manyTimes; $x++) { $handle = fopen($linksList, "r"); $line = fgets($handle); echo $line; fclose($handle); } ?>Hey Guys, I'm stuck on this simple bit of code lol what I'm trying to do is load in a list of urls: site1.com site2.com site3.com etc For each site that is read, I'm trying to duplicate it X times, above would print to screen the same url 1000 times, then move onto the next print it 1000 times etc until the list is done (or how ever many times I select) I can't think of the best way to do it! any help would be appreciated guys! Graham Hi everyone, I don't know whether this is a PHP or MySql problem, but I think it is the former. The following code queries the database correctly, (and before you ask, there are no duplicate database entries), but the output duplicates every row. e.g., hammer (jpg image) hammer hammer (jpg image) hammer saw (jpg image) saw saw (jpg image) saw screwdriver (jpg image) screwdriver screwdriver (jpg image) screwdriver and so on. I cannot see why the code causes the row to repeat. Code: [Select] <?php session_start(); if (isset($_SESSION['id'])) { // Put stored session variables into local php variable $id = $_SESSION['id']; $userId = $_SESSION['userId']; $userGroup = $_SESSION['userGroup']; $managerId = $_SESSION['managerId']; } include_once("demo_conn.php"); $sql = mysql_query("SELECT * FROM users WHERE id='$id'"); while($row = mysql_fetch_array($sql)) { // Get member data into a session variable $egroup = $row["egroup"]; session_register('egroup'); $_SESSION['egroup'] = $egroup; } $query = mysql_query("SELECT topics.url_big, topics.url_small, topics.title, topics.$egroup, quiz.passState, quiz.userDate FROM topics INNER JOIN quiz ON (topics.managerId = quiz.managerId) WHERE topics.$egroup = 1 ORDER BY title ASC"); while ($row1 = mysql_fetch_array($query)) { echo "<a href='../../wood/wood_tool_images/{$row1['url_big']}' target='_blank'><img src='../../wood/wood_tool_images/{$row1['url_small']}' /><br />\n"; echo "{$row1['title']} <br />\n"; } ?> Please help and amend the code Save without repetition required $read[0] I hope that my example is clear to you I apologize for bothering you. I am not good in English <?php $fileLocation = getenv("DOCUMENT_ROOT") . "/rt.txt"; $file = fopen($fileLocation,"a"); $n1 = $_POST['n1']; $n2 = $_POST['n2']; for($i = 0; $i < count($file); $i++){ $read = explode("|", $file[$i]); if($n1 == $read[0]){ echo 'Repetition'; } else { fwrite($file,$n1.'|'.$n2."\r\n"); }
Hi, I need to sort variables in groups of up to 15 and put it in an array. For example: $exstract['center_tabOpBody_0'] =5 $exstract['center_tabOpBody_1'] =6 $exstract['center_tabOpBody_2'] =8 $exstract['center_tabOpBody_3'] =1 Should yield: ARRAY( = center_tabOpBody_1,center_tabOpBody_2,center_tabOpBody_3 // <-----15 [1] = center_tabOpBody_0 //<----5 ) Is there some simple function do do the "efficiency" sort? Thanks, Vadim 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. can you have something like.. echo $whatever; this putput 1.2 can you split this number so the first integer will be in $val"(1)" or whatever and the second integer after the "." will be in $val2"(2)" Hi i got an error. I cant get $new_score and $new_played variables. $name = $_POST["name"]; $score = $_POST["score"]; $result = mysql_query("SELECT * FROM taure_lentele WHERE name='$name'"); $row = mysql_fetch_array($result); if(mysql_num_rows(mysql_query("SELECT name FROM taure_lentele WHERE name='$name'") ) == 1 ) { $old_score = $row['score']; $score + $old_score = $new_score; $old_played = $row['played']; $new_played = $old_played++; mysql_query("DELETE FROM taure_lentele WHERE name='$name'"); mysql_query("insert into `taure_lentele` set `name` = '$name', `score` = '$new_score', `played` = '$new_played"); } Hey, I have checkbox and with these I am setting an exam. I want the questions to contain numbers. So for each question a number would be displayed. So far I am Only getting the question and the choices to display. <html> <?php session_start(); include '../Database/connection.php'; $Value22 = mysql_real_escape_string(trim($_POST['myselects'])); $_SESSION['myselect23'] = $Value22; //echo $_SESSION['myselect23']; ?> <body> <form action="Staff_Menu.php" method="post"> <?php include '../Database/previous_q.php'; while($info = mysql_fetch_array( $sql )) { echo "{$info['Que_Question']} <br />\n"; echo "<input type=\"checkbox\" name=\"choice1[]\" value=\"{$info['Que_Choice1']}\" /> "; echo "{$info['Que_Choice1']} <br />\n"; echo "<input type=\"checkbox\" name=\"choice2[]\" value=\"{$info['Que_Choice2']}\" /> "; echo "{$info['Que_Choice2']} <br />\n"; echo "<input type=\"checkbox\" name=\"choice3[]\" value=\"{$info['Que_Choice3']}\" /> "; echo "{$info['Que_Choice3']} <br />\n"; echo "<input type=\"checkbox\" name=\"choice4[]\" value=\"{$info['Que_Choice4']}\" /> "; echo "{$info['Que_Choice4']} <br />\n"; } ?> <input type="submit" value="submit"/> </body> </html> </body> </html> |