Jump to content

3 randomized fields, no duplicates - buggy! NEED HELP!


phpsyn

Recommended Posts

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();
?>
Link to comment
Share on other sites

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!?!

Link to comment
Share on other sites

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...),
Link to comment
Share on other sites

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?

Link to comment
Share on other sites

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();

?>
Link to comment
Share on other sites

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. 

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.