2015-01-11 47 views
1

我試圖在我的網站中創建每個頁面的唯一URL編號,以便輕鬆地將其包含到網站地圖中。我的網址是這樣的:site.com/book/11111111site.com/book/11111112創建一個唯一的8位數字並將其插入到數據庫中而不會出現重複

我想爲每個ID插入一個唯一的URL,但堅持一個小問題。我使用下面的代碼,但並不保證每次我的thing_url的唯一性。我可以用if-else語句來檢查它的唯一性,但即使我第二次檢查它,我的字符串也可能是第二次也可能不是唯一的。我不想有很多變量和if-else語句使用$thing_url,$thing_url2,$thing_url3等。

有沒有一種方法可以使用單個循環檢查唯一性,直到它成功?這是我現在所做的。

$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 
} 
+3

使用autoincrement id。以下是更多信息http://www.w3schools.com/sql/sql_autoincrement.asp –

+1

我已經爲每條記錄使用了auto_incremented ID,並且它們是唯一的,但我想將這些thing_url用作唯一的URL。 auto_increment ID值很容易猜到,我不希望我的網站內容能夠被輕鬆抓取。 – salep

+2

從1000000到999999爬行ID更困難? –

回答

1

由於這種類型的同步問題,客戶端不應該嘗試生成任何唯一的(除了GUID)。相反,中央協調員應該有這個責任。

在你的情況下,理想的協調者是你的數據庫,MySQL。您可以使用您的URL的主鍵(來自thing_url)作爲唯一標識符。只要數據庫遵循將主鍵遞增1的典型模式,並且以低數字(通常爲1)開始,那就可以正常工作。

我已經爲每條記錄使用了auto_incremented ID,它們是唯一的,但我想使用這些thing_url作爲唯一的URL。 auto_increment ID值很容易被猜出,我不希望我的網站內容容易被抓取。

然後以一些bijective的方式(例如,與一些位模式異或,旋轉位,交換字節等。

相關問題