Snappysites Snappysites - 7 months ago 8
PHP Question

Repeat ID check until available ID found?

This script basically checks to see if the chosen random number already exists as an ID, and if it doesn't, it will add it to the database.

If it finds one that exists, it should repeat the query until it comes back with 0 results.

Here is the script:

$venues_select = unserialize($_COOKIE['album_array']);
foreach ($venues_select as $id) {

$getdetails = mysqli_fetch_assoc(mysqli_query($conn, "SELECT cat_name, cat_city, cat_down_lvl FROM new_categories WHERE cat_id = '$id'"));

$det_cat_name = $getdetails['cat_name'];
$det_cat_city = $getdetails['cat_city'];
$det_cat_id = $getdetails['cat_down_lvl'];

$length = 25;
$randomString = substr(str_shuffle("0123456789"), 0, $length);

$sqla = "SELECT * FROM `new_albums` WHERE `album_ref` = '$randomString'";
$resulta = $conn->query($sqla);

if (!$resulta->num_rows > 0) {

mysqli_query($conn, "INSERT INTO new_albums (album_id,album_name,venue_name,city_name,cat_id,album_ref,date_added)
VALUES ('','$album_name','$det_cat_name','$det_cat_city','$det_cat_id','$randomString','$todays_date')");
} else {

//// CHECK AGAIN
}
}


How would I repeat this code until an available ID has been found?

Answer

Use a while loop:

$search = true; // allow the loop to begin

while($search == true) {
    $randomString = substr(str_shuffle("0123456789"), 0, $length);
    $sqla = "SELECT * FROM `new_albums` WHERE `album_ref` = '$randomString'";
    $resulta = $conn->query($sqla);

     if (!$resulta->num_rows > 0) {

         mysqli_query($conn,"INSERT INTO new_albums (album_id,album_name,venue_name,city_name,cat_id,album_ref,date_added) 
             VALUES ('','$album_name','$det_cat_name','$det_cat_city','$det_cat_id','$randomString','$todays_date')");

        $search = false; // change the flag so the while loop will not repeat

    }
}
Comments