Jump to content

how to generate a random num and make sure it is unique before running through next condition


alexandre
 Share

Recommended Posts

so i have this here: 

$voucher_code = rand(1, 100000000000000000);
if ($stmt = $con->prepare('SELECT voucher_code FROM voucher_codes')) {
	$stmt->bind_param('i', $voucher_code);
	$stmt->execute();
	$voucher_codes = mysqli_query($con, $stmt);
   while (mysqli_num_rows($voucher_codes) > 0) {
 		shuffle($voucher_code);
	}
	if (mysqli_num_rows($voucher_codes) == 0) {
	 			$voucher_code_unique = $voucher_code;
	 		}}

i did not tested it yet , i wanted to know some opinions (if posible for mysqli extension), so what i doubt about this code would be that the query doesnt compare with the shuffled voucher code after it is getting shuffled in case of a duplicated record. if so i would end in a endless loop of same queries to redo and recompare the new generated voucher code from the shuffle function. 

Link to comment
Share on other sites

Putting aside that your code will not work as it is, and that this is very likely the wrong solution for what you're trying to do,

You're dealing with numbers up to 17 digits long. Unless you're generating millions of these, you're not realistically going to get a duplicate. Put it into a loop and it'll work.

Link to comment
Share on other sites

yeah you are right but i have the bad habit to always encounter unprobable things so i was just trying to prevent in case this happens. but what would not work in this code as it is? i know there might be errors i just did this quickly trying to figure the most suitable way to handle this.

Link to comment
Share on other sites

3 hours ago, alexandre said:

what would not work in this code as it is?

Your query binds a parameter it doesn't use, you loop on whether it rows thus it'll either loop forever or not at all, and you're attempting to shuffle a number.

I was hoping you would pay more attention to the part of my post where I said "likely the wrong solution" and less so on the "will not work as is".

Link to comment
Share on other sites

yes i think i should have asked what would work if this is not the good way to go about it ,. and i am always trying to understand whats wrong from where i asked what was wrong with the code it would help to identify an error that i dont want to make again..

Link to comment
Share on other sites

3 hours ago, requinix said:

Your query binds a parameter it doesn't use, you loop on whether it rows thus it'll either loop forever or not at all, and you're attempting to shuffle a number.

I was hoping you would pay more attention to the part of my post where I said "likely the wrong solution" and less so on the "will not work as is".

you are right i didnt put a where clause...

Link to comment
Share on other sites

about shufling a number generated randomly using range , i thought that if i shuffled the number it would give a new number in that range but , it seems like we cant do this. what would be your way of doing this ? i find it intriguing since this seems quite a simple solution if i make it right no?

Link to comment
Share on other sites

If you ever get around to looking at the PHP manual and look up "shuffle()" yo will see its description is

This function shuffles (randomizes the order of the elements in) an array.

As it is randomising what you already have (ie a random number) what are you gaining?

The second thing to note in the description is that it is for shuffling the elements of an array, not the characters in a string.

Link to comment
Share on other sites

6 minutes ago, Barand said:

Answer: The first line only. The rest is a hotch-potch of pasted code with no thought for what each line does or what the variables contain.

thats not true , i thought about the behavior of what i was trying to do should be but obviously i didnt read the manual for the shuffle function , i saw it in an example somewhere on a forum while looking for an answer already answered but he was doing this shuffle($numbers) in the answer so i just assumed it was a shuffling function. and for the rest i dont see why it is what you said hotch-potch ? yes i save time by going in my other files and taking a part of code that i need sometimes but for the most part i dont copy paste only. the idea behind it makes sense for me .. i just was looking for theorical enlightement  to have a better understanding and it seems like it worked .😅

Link to comment
Share on other sites

Do you know how to read the manual to understand how functions work?  You are demonstrating not much of a capability to program with this example.  Let me add some comments that might make you see what you are doing here.  I am being rough but you already have an open topic on this forum and like some other people here you have begun a new adventure that is sending you off in a peculiar direction while your first topic is still hanging.

$voucher_code = rand(1, 100000000000000000);
// You are seeking a random number in a range that most systems can't even fathom due to integer size limits
//  per the PHP manual the max int is: 9223372036854775807 and you are exceeding that
if ($stmt = $con->prepare('SELECT voucher_code FROM voucher_codes'))
// you are querying for every row in your voucher_codes table
{
	$stmt->bind_param('i', $voucher_code);
	//  you are binding a value to what ????
	$stmt->execute();
	//  you have just run your query
	$voucher_codes = mysqli_query($con, $stmt);
	//  and now you are running your query again
	while (mysqli_num_rows($voucher_codes) > 0)
	{
		shuffle($voucher_code);
		//  you are shuffling a single digit that was selected at random and has nothing to do with the query  
		//  Over and Over and Over and Over and Over......
	}
	if (mysqli_num_rows($voucher_codes) == 0)
	{
		$voucher_code_unique = $voucher_code;
		// since your query resulted in no hits (how could that be?) you
		// are assigning your random number to a desired variable that 
		// you don't assign a 'hit' to when there are any
	}
}
//  all of the code above is only run if your prepare 'works'
//  What are you going to do if the prepare fails?

AND in your response to my critique (criticism?) PLEASE don't re-post my post.  We can all see it here.

Link to comment
Share on other sites

first of all you attack me about something that i wasnt even done writing , i was asking for opinions to be sure i was going the right way ., which i got, and now i will go work on it , no need of telling me that i dont know to do nothing in programming , and yes i was extremely tired last night and didnt pay much attention so i am sorry for asking for enlightment for no reason..

Link to comment
Share on other sites

6 minutes ago, ginerjm said:
per the PHP manual the max int is: 9223372036854775807 and you are exceeding that

I don't see how...

100000000000000000
9223372036854775807

 

9 minutes ago, ginerjm said:
$voucher_codes = mysqli_query($con, $stmt);
	//  and now you are running your query again

He isn't running it again - he attempting to run a query on a statement object instead of a string of SQL.

Link to comment
Share on other sites

the OP is trying to do this activity by rote, by memorization, by appearance, not though actually learning (internalizing) the meaning of the words and syntax. this produces a result that is only as good as his memory recall is. the mysqli_query() call on the prepared query statement object is the same misusage at the start of a previous recent thread, which @requinix hinted/asked (Jeopardy theme can be heard playing in the background) if the OP actually wanted to do this. one would assume that since the OP removed this statement in that thread that he would have learned something by doing so, but since the OP is doing this by repeating pictures of the words, no learning occurred, hence the repeated mistake.

@alexandre, writing code actually means writing the words and syntax of the language you are using, so that they result in an understandable story that when the computer executes them they do something useful. to do this you must actually learn the meaning of the words and syntax, not just repeat, copy/pasting things together based on what you have seen. somehow, you must make this transition in how you are approaching this activity. instead of  just seeing and repeating a picture of the words, you must actually learn the meaning of the words, so that you know what they do or even if they belong in the current task.

Link to comment
Share on other sites

what your code should do for this activity is generate a random number, then do what is described in this post - https://forums.phpfreaks.com/topic/315552-php-mysql-returns/#comment-1602746 to just attempt to insert that random number into the table. if the code continues past the point where the INSERT query is executed, you know that the generated number was unique and was inserted into the table. if the code transfers execution to the exception catch block and the error number is for a duplicate index, instead of setting up a message for the user that there was a duplicate, you would cause the code to loop back to the start, where it would generate a new random number and attempt to execute the insert query again. i would use a loop counter, of about 10, so that a programming mistake or the random number generator doesn't work very well (the rand() documentation mentions that the maximum on windows is a 32bit number, not a double-int) to force an exit if the operation doesn't succeed. 

 

Edited by mac_gyver
Link to comment
Share on other sites

maybe this should look better

$voucher_code = rand(0, 1000000000000000000);
$stmt = $con->prepare('SELECT voucher_code FROM voucher_codes WHERE voucher_status = 1');
	$voucher_codes = mysqli_query($con, $stmt);
   if (mysqli_num_rows($voucher_codes) > 0) {
		 while ($voucher_rows = mysqli_fetch_assoc($voucher_codes)) { 
 		if ($voucher_code === $voucher_codes) {
			unset($voucher_code);
			$voucher_code = rand(0, 1000000000000000000);
		}
		else if ($voucher_code != $voucher_codes) {
		 			$voucher_code_unique = $voucher_code;
	}
}
}

and yes im starting to get the difference with mysqli objects.. i think so 😅

Link to comment
Share on other sites

1 hour ago, mac_gyver said:

what your code should do for this activity is generate a random number, then do what is described in this post - https://forums.phpfreaks.com/topic/315552-php-mysql-returns/#comment-1602746 to just attempt to insert that random number into the table. if the code continues past the point where the INSERT query is executed, you know that the generated number was unique and was inserted into the table. if the code transfers execution to the exception catch block and the error number is for a duplicate index, instead of setting up a message for the user that there was a duplicate, you would cause the code to loop back to the start, where it would generate a new random number and attempt to execute the insert query again. i would use a loop counter, of about 10, so that a programming mistake or the random number generator doesn't work very well (the rand() documentation mentions that the maximum on windows is a 32bit number, not a double-int) to force an exit if the operation doesn't succeed. 

 

i will take a better look at this , this seems to be the behavior i wish to produce.

also my  choucher_code collumn is already a unique one

Edited by alexandre
Link to comment
Share on other sites

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.

 Share

×
×
  • 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.