使用 while() 生成随机文件名?
我使用 while() 循环创建一个随机文件名,根据数据库检查它,然后如果它已经存在,则循环。我只是有点担心我的语法/用法不对,因为很久以前我只做过一次,并且从那时起就没有以这种方式使用过 while() 循环。
这是我的代码:
$i = 0;
while(++$i) {
$file_name = md5(mt_rand(0,9999999)) . ".php";
$result = mysql_query("SELECT * FROM x WHERE file_name = '{$file_name}'");
if(mysql_num_rows($result) == 0) { break; } else { continue;}
}
这行得通吗?如果不行,有什么问题吗?
我知道这是一个小问题,但测试这是否有效似乎更加“任务繁重”(需要创建一个新表,更改文件名以从 1 - 3 个内容中进行选择,显示一条消息而不是继续等 ,任何帮助将不胜感激!
一如既往
I'm using a while()
loop to create a random file name, check it against a database, then if it already exists, loop. I'm just a little worried my syntax/usage is off, as I've only done this once before ages ago, and haven't used a while()
loop in this way since then.
Here's my code:
$i = 0;
while(++$i) {
$file_name = md5(mt_rand(0,9999999)) . ".php";
$result = mysql_query("SELECT * FROM x WHERE file_name = '{$file_name}'");
if(mysql_num_rows($result) == 0) { break; } else { continue;}
}
Would this work, and if not, what's wrong with it?
I know it's a petty question, but testing out whether or not this would work seems a lot more "tasky" (need to create a new table, alter the file name to choose from 1 - 3 things, display a message instead of continue etc.
Any help, as always, would be appreciated!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
你不需要
$i
,因为你没有使用它,并且你不需要在循环中continue
- 循环会自动循环,这就是什么确实如此。当您达到想要结束循环的条件时,您只需要break
:不过,您使用散列的方式略有破坏。您应该生成一个比 MD5 哈希值更长的随机字符串,而不是更短。现在,您只有 10,000,000 个可能的文件名 (0..99999999),而不是 MD5 可以生成的完整 2^128 个文件名。不必担心 2^128 这样大的空间中的哈希冲突,您更有可能简单地生成相同的数字两次,从而导致多次访问数据库。
You don't need
$i
, since you're not using it, and you don't need tocontinue
in a loop - the loop will automatically loop, that's what it does. You only need tobreak
when you reach the condition under which you want to end the loop:You're using hashes in a slightly broken way though. You should be generating a random string longer than an MD5 hash, not shorter. Right now you only have 10,000,000 possible filenames (0..99999999) instead of the full 2^128 that a MD5 can produce. Instead of worrying about hash collisions in a space as large a 2^128, you have a much higher chance of simply generating the same numbers twice, causing multiple trips to the database.
采用代码所做的方法也比必要的更“任务繁琐”,但为什么不让数据库为您完成“创建唯一文件 ID”的工作
?列哪个是
bigint(20) auto_increment
或类似的内容,然后在 PHP 代码中发出查询来创建新行,获取保证唯一的数字 ID,并将其转换为文件名。Taking the approach that the code does is also more "tasky" than necessary. It's workable, but why not let the database do the "create a unique file ID" work for you?
Define the file_name column in x to instead be a file_id column which is
bigint(20) auto_increment
or something like that. Then in the PHP code, issue a query to create a new row, grab the guaranteed-unique numeric ID, and transform it into a file name.这将起作用,但您可以将行: while(++$i) 更改为 while(true)
This will work but you can change the line: while(++$i) into while(true)