首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >PHP/SQL重复循环,直到数据在PHP中唯一或即席创建SQL查询

PHP/SQL重复循环,直到数据在PHP中唯一或即席创建SQL查询
EN

Stack Overflow用户
提问于 2012-10-15 15:30:32
回答 3查看 655关注 0票数 0

我需要为用户生成关键代码,所以我需要在数据库中是唯一的。

我需要重复这个循环,直到key唯一:

代码语言:javascript
复制
create key;

if($key is not in db){

  insert key;

}else{

repeat control with new key;

}

我想过while(),但不明白如何实现它。

插入数据库唯一键和更新数据库唯一键的其他方法可以直接在sql查询中编写,而不是使用php脚本?(使用Sql查询插入/更新唯一键)

希望是一个清晰的问题。

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2012-10-15 15:33:25

代码语言:javascript
复制
$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 (这意味着密钥不是数据库中存在的唯一密钥),我们就会创建一个新的唯一密钥并反复检查它。

票数 4
EN

Stack Overflow用户

发布于 2012-10-15 15:37:00

尝试只使用UUID

或者在数据库中的列上添加唯一约束,并继续尝试插入行,直到没有mysql错误为止

代码语言:javascript
复制
do {
    //insert using uniqid() or some random string
} while( $check_for_mysql_error );
票数 2
EN

Stack Overflow用户

发布于 2012-10-15 15:34:33

代码语言:javascript
复制
/**
 * 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;
    }
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/12891050

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档