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!
You don’t need
$i, since you’re not using it, and you don’t need tocontinuein a loop – the loop will automatically loop, that’s what it does. You only need tobreakwhen 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.