How to check if value exists in DB with a loop?

I generate a random string but I need to check if it exists in DB and keep generating until it doesn’t and then insert. This must be done somehow with a loop. But I can’t think of how to do it.

public function checkEncryptId($encryptId) {
    $sql = "SELECT encrypt_id FROM table WHERE encrypt_id = :encryptId";
    $result = $this->connect()->prepare($sql);
    $result->bindParam(":encryptId", $encryptId, PDO::PARAM_STR)
    $result->execute();
    $data = $result->fetch(PDO::FETCH_ASSOC);
    if(!$data) {
        return false;
    }
    return true;
}

$length = rand(5, strlen($_GET['encrypt']));
$encryptId = $this->generateRandomString($length);
$uniqueEncryptId = $this->checkEncryptId($encryptId);
if ($uniqueEncryptId) {
   echo 'found';
};
if($this->insertData($encryptId, $encryptedMsg)) {
    echo json_encode($encryptId); 
    return false;
};

>Solution :

Put the code that generates and checks the string in a loop. Break out of the loop when the ID isn’t found.

while (true) {
    $encryptId = $this->generateRandomString($length);
    if (!$this->checkEncryptId($encryptId)) {
        break;
    }
}
if($this->insertData($encryptId, $encryptedMsg)) {
    echo json_encode($encryptId); 
    return false;
};

Leave a Reply