我需要为用户生成关键代码,所以我需要在数据库中是唯一的。
我需要重复这个循环,直到key唯一:
create key;
if($key is not in db){
insert key;
}else{
repeat control with new key;
}我想过while(),但不明白如何实现它。
插入数据库唯一键和更新数据库唯一键的其他方法可以直接在sql查询中编写,而不是使用php脚本?(使用Sql查询插入/更新唯一键)
希望是一个清晰的问题。
发布于 2012-10-15 15:33:25
$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循环,请记住:
while(表达式)
只要表达式返回true,我们就会进入循环。因此,只要我们的自定义函数this_key_exists (返回true或false)返回true (这意味着密钥不是数据库中存在的唯一密钥),我们就会创建一个新的唯一密钥并反复检查它。
发布于 2012-10-15 15:37:00
尝试只使用UUID
或者在数据库中的列上添加唯一约束,并继续尝试插入行,直到没有mysql错误为止
do {
//insert using uniqid() or some random string
} while( $check_for_mysql_error );发布于 2012-10-15 15:34:33
/**
* 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;
}
}https://stackoverflow.com/questions/12891050
复制相似问题