我会生成一个随机的字符串,但是我需要检查它是否存在于DB中,并继续生成直到不存在然后插入。必须以循环以某种方式完成此操作。但是我想不出怎么做。

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;
};
分析解答

将生成并在循环中检查字符串的代码。找不到ID时突破循环。

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