我需要为用户生成密钥代码,所以我需要它在数据库中是唯一的。
我需要重复这个循环,直到键是唯一的:
create key;
if($key is not in db){
insert key;
}else{
repeat control with new key;
}
我想到了 while() 但不明白如何实现它。
插入数据库唯一键和更新数据库唯一键的其他方法可以直接用 sql 查询而不是使用 php 脚本编写?(使用 Sql 查询插入/更新唯一键)
希望是清楚的问题。
我需要为用户生成密钥代码,所以我需要它在数据库中是唯一的。
我需要重复这个循环,直到键是唯一的:
create key;
if($key is not in db){
insert key;
}else{
repeat control with new key;
}
我想到了 while() 但不明白如何实现它。
插入数据库唯一键和更新数据库唯一键的其他方法可以直接用 sql 查询而不是使用 php 脚本编写?(使用 Sql 查询插入/更新唯一键)
希望是清楚的问题。
$key = create_unique_key();
while( this_key_exists($key) )
{
$key = create_unique_key();
}
//If you got here - the value of $key is unique and doesn't exist in db
说明:您首先使用自定义函数创建了一个唯一键create_uniuqe_key,所以现在我们有了 的起始值$key。其次,我们有一个while循环,请记住:
而(表达式)
只要表达式返回 true,我们就会进入循环。因此,只要我们的自定义函数this_key_exists(返回 true 或 false)返回 true(这意味着 - 密钥不是 uniuqe - 存在于数据库中),我们将创建一个新的唯一密钥并一次又一次地检查它。
尝试仅使用UUID
或在数据库中的列上添加唯一约束并继续尝试插入行,直到没有mysql错误
do {
//insert using uniqid() or some random string
} while( $check_for_mysql_error );
/**
* Creates a unique URL for a page language by adding a 'dash number'
* at the end of the provided user URL
* @param string $page The current page
* @param string $url The URL to make unique
* @param type $lang The language to make unique for (you can have the same URL for same page in diffrent languages)
* @return string The new URL
*/
function uniquePageUrl($page, $url, $lang){
while(TRUE){
$result = $this->db->from('pages')->where('page <>', $page)->where('lang',$lang)->where('url',$url)->limit(1)->get()->row();
if($result) //we already have a page URL for this language like the one we try to use
$url = increment_string($url,'-');
else
return $url;
}
}