phpsyn Posted September 2, 2014 Share Posted September 2, 2014 Hello I am working on a 3 field variable that is given in an array with A-Z and 1-26 and 26 words in total, being randomized and insert in database via mysql but it must checks to be sure there is no duplicate of any values at all. here is my code, I managed to make the first value to work but the 2nd and 3rd doesnt. <? // connection data mysql_connect("localhost", "user", "pass") or die("error ".mysql_error()); mysql_select_db("dbname") or die("error ".mysql_error()); function GenerateNumber(){ // selects random number $randomNumber = rand(1,26); return $randomNumber; } function GenerateLetter(){ // selects random position number in letters array to select an alphabet $LetterPosition = rand(0,25); $alphabet = array('a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'); $randomLetter = $alphabet[$LetterPosition]; return $randomLetter; } function GenerateWord(){ // selects random word from an array -same method as letter $wordPosition = rand(0,25); $words = array('ah','book','cup','dice','elephant','flute','gum','house','idol','jumpingjacks','kite','lunchbox','matress','novel','olive','pumpkin','queen','rooster','stove','teacup','unicorn','violin','walurus','xerox','zebra'); $randomWord = $words[$wordPosition]; return $randomWord; } for($x=0; $x<=25;){ //generate letter,number,and word $randomLetter = GenerateLetter(); $randomNumber = GenerateNumber(); $randomWord = GenerateWord(); echo '<b>Generated Variables:</b>[ '. $randomLetter.' ][ '.$randomNumber.' ][ '.$randomWord.' ]<br />'; // there is data in the table, check if there is letter already assigned $first = mysql_query("SELECT * FROM test WHERE a_char='$randomLetter'"); if(mysql_num_rows($first) == 0){ //no letter is found, check if there is number already assigned $second = mysql_query("SELECT * FROM test WHERE aint='$randonNumber'"); if(mysql_num_rows($second) == 0){ //no number is found, check if there is word already assigned $thrid = mysql_query("SELECT * FROM test WHERE aword='$randomWord'"); if(mysql_num_rows($third) == 0){ //there is no letter,number, and word found in db, great! go ahead and insert! $fq = "INSERT INTO test (a_char,aint,aword) VALUES ('$randomLetter','$randomNumber','$randomWord')"; $final = mysql_query($fq); //increment the loop $x++; echo('[ '. $randomLetter.' ][ '.$randomNumber.' ][ '.$randomWord.' ] has been added in row '.$x.'<br /><br />'); }else{ echo("Repeated Word: ".$randomWord." generating another: "); //there is word already assigned, select another! $randomWord = GenerateWord(); echo($randomWord.'<br /><br />'); } }else{ echo("Repeated Number: ".$randomNumber." generating another: "); //there is number already assigned, select another! $randomNumber = GenerateNumber(); echo($randomNumber.'<br /><br />'); } }else{ echo("Repeated Letter: ".$randomLetter." generating another: "); //there is letter already assigned, select another! $randomLetter = GenerateLetter(); echo($randomLetter.'<br /><br />'); } } mysql_close(); ?> Quote Link to comment Share on other sites More sharing options...
mentalist Posted September 2, 2014 Share Posted September 2, 2014 Not properly looked but why "$x<=25", that's only enough for the first set to be unique, not all three sets which are calc'd in the loop... I'd personally use a "while" loop probably... Also the checks which get a second random are basically redundant since once passed them it regenerates another anyway at the begining of the loop!?! Quote Link to comment Share on other sites More sharing options...
Ch0cu3r Posted September 2, 2014 Share Posted September 2, 2014 It is a bad idea using queries in loops. Instead you should first add the random values to arrays. Use in_array to check if the value has been generated before. Then you can insert all the random combinations using one query eg INSERT INTO table (col1, col2, col3) VALUES (...combination 1...), (...combination 2...), (...combination 3...), Quote Link to comment Share on other sites More sharing options...
phpsyn Posted September 2, 2014 Author Share Posted September 2, 2014 Ch0cu3r: I do not understand your example for combination 1,2,3 --however: I got what you mean for the first random row then check in_array. but I do not SEE how it is done. can you help by giving me an example for me to use and play with? Quote Link to comment Share on other sites More sharing options...
Jacques1 Posted September 2, 2014 Share Posted September 2, 2014 The whole approach doesn't make a lot of sense. So you generate random combinations over and over again in the hopes that you eventually get a unique combination? Why not just shuffle the three arrays and then combine the elements one by one? shuffle(). Quote Link to comment Share on other sites More sharing options...
phpsyn Posted September 2, 2014 Author Share Posted September 2, 2014 I decided to go with the dump array and in_array approach and it worked like a charm, I really am happy with this results: <? // connection data function conn(){ mysql_connect("localhost", "user", "pass") or die("error ".mysql_error()); mysql_select_db("database") or die("error ".mysql_error()); } function GenerateNumber(){ // selects random number $randomNumber = rand(1,26); return $randomNumber; } function GenerateLetter(){ // selects random position number in letters array to select an alphabet $LetterPosition = rand(0,25); $alphabet = array('a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'); $randomLetter = $alphabet[$LetterPosition]; return $randomLetter; } function GenerateWord(){ // selects random word from an array -same method as letter $wordPosition = rand(0,25); $words = array('ah','book','cup','dice','elephant','flute','gum','house','idol','jumpingjacks','kite','lunchbox','matress','novel','olive','pumpkin','queen','rooster','stove','teacup','unicorn','violin','walurus','xerox','yellow','zebra'); $randomWord = $words[$wordPosition]; return $randomWord; } // --------purge before usage----- // conn(); mysql_query("DELETE FROM test"); mysql_close(); ////////////////////////////////////// //intializiation $result = array(); $dump = array(); $end = false; $x=0; conn(); while($end != true){ //generate Letter, Number, and word $randomLetter = GenerateLetter(); $randomNumber = GenerateNumber(); $randomWord = GenerateWord(); if(in_array($randomLetter,$dump)){ $randomLetter = GenerateLetter(); }else{ if(in_array($randomNumber,$dump)){ $randomNumber = GenerateNumber(); }else{ if(in_array($randomWord, $dump)){ $randomWord = GenerateWord(); }else{ array_push($dump,$randomLetter); array_push($dump,$randomNumber); array_push($dump,$randomWord); mysql_query("INSERT INTO test (a_char,aint,aword) VALUES ('$randomLetter','$randomNumber','$randomWord')"); $x++; } } } if($x == 26){ $end = true; } } echo '<br /><br />RESULTS: <br />'; //debug to see if data is inserted correctly (in HTML) $r=mysql_query("SELECT * FROM test"); while($row = mysql_fetch_assoc($r)){ echo '[ '.$row['a_char'].' ][ '.$row['aint'].' ][ '.$row['aword'].' ]<br />'; } mysql_close(); ?> Quote Link to comment Share on other sites More sharing options...
Jacques1 Posted September 2, 2014 Share Posted September 2, 2014 It's fascinating that whenever you give a PHP programmer a choice, they always pick the worst possible option. The entire task could be done in 10 lines of code and 10 minutes of your time. But, no, we don't want that. We want 100 lines of code, we want to work on it for 2 hours, and we want to turn the whole thing into a friggin' lottery: Will we be lucky this time and get three unique elements? I understand that you're new to PHP. But isn't this a matter of common sense? There's a short, simple and fast solution. And there's a long, ugly and slow solution. Now, which one is preferrable? I'm sorry for addressing you personally, this is not about you specifically. But I see this pattern over and over again, and I wonder what on earth is going on. Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.