PHP generateCode


/ Published in: PHP
Save to your folder(s)

Some times you need to generate a code for a field in a db and that code can't be repeated either...

Yes, I know that if two people submit their data at almost the exact same time that it could be possible that they have the same code. OMG OMG OMG! I'll take the 0.0000000001% chance that it will happen. You could get around this by generating a separate table of pre-made codes and each time you use one you take it and mark it as used.


Copy this code and paste it in your HTML
  1. /** Simple function to generate a code and check if it is already used. If so
  2.   * generate a new one.
  3.   *
  4.   * $table the database table that you are working on
  5.   * $field the field that contains the codes
  6.   * $length the length of the code you want. should be less that the possibilities
  7.   * $chars the string that you want to choose chars from
  8. **/
  9. function generateCode( $table , $field , $length = 7 , $chars = "ABCDEFGHJKMNPQRTUVWXYZ2346789" )
  10. {
  11. // generate a code
  12. $temp = substr( str_shuffle( $chars ) , 0 , $length );
  13.  
  14. // test if it has been used already
  15. $q = "SELECT ".$field." FROM ".$table." WHERE ".$field." = '".$temp."'";
  16.  
  17. $qr = dbquery( $q ); //dbquery is my function to call queries...
  18. if( mysql_num_rows( $qr ) == 0 )
  19. {
  20. return $temp; // not used return it
  21. }
  22. else
  23. {
  24. return generateCode( $table , $fields, $length , $chars ); // used try again
  25. }
  26.  
  27. }
  28.  
  29.  
  30. // the chars string above is regarded in the marketing biz as being the most easily
  31. // readable so no 5S I1 O0 stuffs

URL: http://www.itsgotto.be/cv.php

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.