0

I need to make a key generator, and I need to check from the database that that key does not exist. If the key already exists, I want to generate another key and check if that one exists, until I get one that does not exist. This is what I have, and it's not returning anything if it exists.

function checkHash($hash) {
    include 'config.php'; //This calls for the DB
    $checkhash = "SELECT * FROM orders WHERE uuid='$hash'";
    $resultcheck = mysqli_query($db, $checkhash);
    if(mysqli_num_rows($resultcheck) == 0) {
        return $hash;
    } else {
        $orderhash = generateRandomString("15"); //The function that generates the key is generateRandomString();
        checkHash($orderhash); //This re-runs the check function with a new key
    }

    echo generateRandomString("15"); //The 15 means how many characters in the key
Barmar
  • 741,623
  • 53
  • 500
  • 612
Francisco F.
  • 111
  • 1
  • 3
  • 14
  • You're not telling it to return anything if it exists. In your else, make sure you `return checkHash($orderhash);` – rickdenhaan Jun 09 '17 at 19:47
  • I did that, but it didn't run the function again – Francisco F. Jun 09 '17 at 19:47
  • It might be easier to use a do/while loop instead of reiterating the call. – aynber Jun 09 '17 at 19:48
  • If your strings are random enough (like actual UUIDs) you generally don't need to check the database every time you need a new one. Just attempt the insert and catch the condition where it fails due to duplicate key. You'll probably never have that happen but you'll save a ton of reads. – Alex Howansky Jun 09 '17 at 19:52
  • By the way, MySQL actually has a [UUID](https://dev.mysql.com/doc/refman/5.7/en/miscellaneous-functions.html#function_uuid) function to create a unique ID, if you don't need to create your own. – aynber Jun 09 '17 at 19:54

0 Answers0