Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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;
};
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading