I am trying to create a unique URL number of each page in my website to include it into a sitemap easily. My urls look like this : site.com/book/11111111
, site.com/book/11111112
I want to insert a unique URL for each ID, but stuck with a little problem. I use the code below, and it doesn't guarantee the uniqueness of my thing_url
for every time. I can check its uniqueness with an if-else statement but even I check it for the second time, my string may or may not be unique for the second time, either. I don't want to have lots of variables and if-else statements using $thing_url
, $thing_url2
, $thing_url3
, etc.
Is there a way to check the uniqueness using a single loop, until it succeed? Here's what I do now.
$thing_name = $_POST['thing_name']; // form value
$thing_url = mt_rand(10000000, 99999999); // generates 8 digit numeric string
$query = "SELECT thing_url FROM thing WHERE thing_url = '$thing_url'";
$result = $sqli->query($query);
$row = $result->fetch_assoc();
$finish = $row['thing_url'];
if($finish == $thing_url) {
echo "Bad luck";
} else {
$thing = $sqli->prepare("INSERT INTO thing(thing_url, thing_name ) VALUES (?,?)"); // prepare
$thing->bind_param("ss", $thing_url, $thing_name); // bind
$thing->execute(); // execute
$thing->close(); // close
}