Insert a record in a field that must be between 10000 - 99999 and no longer exists in unique field records
2 answers
It should be optimized, but basically you want code like (pseudocode):
// lock table to prevent duplicates
mysql_lock_table('table');
do {
$random = rand(10000, 99999);
} while ( mysql_count_rows("SELECT count(*) FROM table WHERE unique_no = %value", $random) > 0 );
$row['unique_no'] = $random;
mysql_insert($row);
// unlock table
mysql_unlock_table('table');
If the table has a UNIQUE key in the field, you can use INSERT IGNORE
with the specified row values
// lock table to prevent duplicates
do {
$random = rand(10000, 99999);
$row['random'] = $random;
$result = mysql_insert_ignore($row);
} while ( mysql_affected_rows($result) == 0 );
0
source to share