I have a system that generates a batch of random codes up to 100 at a time. They are then inserted in to a database. I am using a code generator and it would be pretty unlikely a similar code could be created again but to make sure I want to check the DB for a duplicate anyway. My theory..
$amount_of_codes
while ($x != $amount_of_codes)
{
$code = gencode();
$mysql_check = "SELECT code FROM data WHERE code = '$code'";
$mysql_check_result = mysql_query($mysql_check);
$check = mysql_num_rows($mysql_check_result);
if (!$check)
{
mysql_query("INSERT INTO data(code) values('$code')")
$x++
}
}
seems messy, any better ideas?
Give the
CodeColumn a UNIQUE constraint:When inserting you only need to capture database exceptions/errors, not worrying if a Code already exists.