How to write a function that would generate a promotional code, and check it for uniqueness in the database, if it found a match, then generate it again and check again.

If after checking for the database no matches were found, a record would occur.

Tell me how to write a function correctly.

There is a code:

function gen_code($length = 7){ $num = range(0, 9); $symbols = array_merge($num, $_alf); shuffle($symbols); $code_array = array_slice($symbols, 0, (int)$length); $code = implode("", $code_array); return $code; } $resultStat = $mysqli->query("SELECT id,promocode FROM stat WHERE promocode !== '0' and hash_person = '$global_id_visit' and idp = '$idp'"); // если находит промо код. if ($resultStat->num_rows) { $rowStat = $resultStat->fetch_assoc(); // удаляем из поля код. $mysqli->query("UPDATE stat SET promocode = '0' WHERE id = $rowStat['id']"); // заносим его в переменную $promocode = $rowStat['promocode']; } else { // если не находим код, то генерируем новый $promocode = gen_code(5); // проверяем с генерированный код на совпадение. $checkStatCT = $mysqli->query("SELECT id,promocode FROM stat WHERE promocode == '$promocode' and idp = '$idp'"); if ($resultStat->num_rows > 0) { $promocode = gen_code(5); } } 

Maybe take all the promocode from the database, put them into the array and pass to the function, already in it do a check for a match, but how to add this piece to the generation function?

  • use count when querying if matches are greater than 0, then rewrite - Vadim
  • so it turns out I need to re-generate it ... - Alexander Sizintsev
  • yes it turns out so - Vadim
  • honestly did not understand how ... can you show in the code? - Alexander Sizintsev

0