开发者

PHP if a value exists in database, how can i rename a new value in sequence?

I have a feild in a mySQL table for file names, when new files are uploaded a function checks if that filename already exists. How can i change the new filename if the same exists to something like:

filename.jpg, filename_(1).jpg, filename_(2).jpg etc

I get most of how to do it, just not sure howto make the function that renames it know what开发者_StackOverflow中文版 number is in filename (if any) and what the next number is to change it to.

Cheers


The simplest answer is to generate unique filenames when they're uploaded, using some combination of the time and user. Maybe something like:

$user_id . time() . $user_provided_name . "." . $file_type


If you probe the existence of the files with file_exists() in a loop then you could include this to increase the numeric suffix:

$filename = preg_replace('# (_\(  (\d+)  \))?  (?=\.\w+$) #ex',
            '"_(" . ($2+1) . ")"', $filename, 1);

The same can be accomplished with strpos/substr functions. And it probably would look less like gibberish.


You can use a COUNT:

SELECT COUNT(*) AS NumberFiles FROM Files WHERE FileName = '$filename'

Then, on your query result, use the $result[0]['NumberFiles'] to rename your file.

You might also want to LOCK your Files table (or whatever it is).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜