创建随机字符串,检查它是否存在,如果存在则创建一个新字符串
我想生成一个大约 5 个字符长的随机字符串。我可以正常创建它,但我无法检查它是否存在于数组(或实际情况下的数据库)中,并在存在时创建一个新数组。
我使用这样的函数来生成字符串:
function rand_string(){
return substr(md5(microtime()), 0, 5);
}
但我迷失了。
- 我需要检查它是否已经存在。
- 如果是,则制作一个新的
- 并重复
I want to generate a random string of about 5 characters long. I can create it ok, but I'm having trouble checking if it exists in an array (or database in real situation) and creating a new one if it does.
I use a function like this to generate the string:
function rand_string(){
return substr(md5(microtime()), 0, 5);
}
But them I'm lost.
- I need to check if it exists already.
- If it does, make a new one
- And repeat
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
试试这个:
Try this:
只是警告,如果您使用它来生成唯一的字符串,一旦确定它没有被使用,就将其添加到数据库中,那么这在并发环境中是不安全的。
在您检查它不在数据库中以及稍后在另一个线程上添加包含它的记录之间的时间间隔中可以执行相同的操作...
如果您以这种方式使用它,可能最安全的方法是确保包含字符串的字段对它有一个独特的约束并尝试添加它。如果您成功添加它,那么您就知道它是唯一的,如果没有,那么它就不是。这在多线程环境中是安全的。
如果您只是检查静态字符串列表并且不打算将生成的字符串添加到数据库中,那么请忽略这篇文章:P
Just a warning that if you are using this to generate a unique string by adding it to the database once you've determined it's not been used then this is not safe in a concurrent environment.
In the interval between you checking it's not in the database, and adding a record containing it later on another thread could do the same...
If you are using it this way, probably the safest approach is to ensure that the field containing the string has a unique constraint on it and try to add it. If you suceeded in adding it then you know it was unique, if you didn't then it wasn't. And this is safe to do in a multithreaded environment.
If you are simply checking against a static list of strings and do not intend to add the generated string to the database then ignore this post :P
要检查它是否在数据库中,请运行查询。
To check if it's in the DB run a query after.
在数据库上,您可以..:
获取新字符串并检查..:
围绕它构建一段时间,然后就完成了
on a database you could..:
for a new string and to check..:
build a while around it and you'Re done
通过 mysql_query(),使用 select 语句查看是否返回任何结果(即“Select * from table where col1 = 'String'”。然后测试以查看是否返回任何行。循环这些调用,直到获得结果)一个真正随机的、未使用的值。
With the mysql_query(), use a select statement to see if you return any results (i.e., "Select * from table where col1 = 'String'". Then test to see if any rows were returned. Loop through these calls until you have a truly random, unused value.