Repeat until successful

Howdy all,

I have written the following code to put in a random value into mysql. The “pin” field is set to UNIQUE, and I need this script to repeat itself until it has successfully inserted a record on $querypass.

[php]
{
$aa = better_urandom_rand(0xFFFFFFFE,0xFFFFFFFE);
$querypass = “INSERT INTO collision_test_pass (pin) VALUES ($aa)”;
$queryfail = “INSERT INTO collision_test_fail (pin) VALUES ($aa)”;
if (!mysqli_query($link, $querypass)) {
mysqli_query($link, $queryfail);
}
}[/php]

Could someone please point me in the right direction?

My sample uses PDO, but other than that works. There are two ways to handle it, and I dont know where your implementation is meant to fall. Option 1, query the database to see if the value already exists. Option 2, do an UPSERT.

Option 1:
[php]
function random( $min = 1, $max = 20)
{
return rand( $min, $max);

}

try {

    do {

        $pin = random();

        $stmt = $db->prepare('SELECT COUNT(*) FROM upsert WHERE pin = :value');
        $stmt->execute(array(':value' => $pin));

        if ($stmt->fetchColumn() == 0) {
            echo "Insert Successful!<br>";

            $stmt = $db->prepare("INSERT INTO `test`.`upsert` ( `pin` ) VALUES ( :value )");
            $stmt->execute(array(':value' => $pin));
        } else {
            echo "Insert Failed<br>";
        }

    } while ($stmt->fetchColumn() != 0);


} catch (Exception $e) {
    error_log( $e->getTrace() );
}

[/php]

I must be missing something, but the sample seems to give either “success” or “failure.” If the number already exists, then I want the script to make another random number and try to insert again.

Perhaps I didn’t make myself clear.

That is what it does, it is just verbose doing so. If the pin exists already, it grabs another and tries to insert again.

Sponsor our Newsletter | Privacy Policy | Terms of Service