处理前检查条目
嘿伙计们! 我有一个应该将图像添加到数据库中的脚本。它就是这样做的。唯一的问题是它不仅添加新图像,而且还添加现有图像。 我确信这对您来说是一项非常简单的任务,但对我来说却太多了!
因此,这段代码应该再次检查条目是否存在,如果不存在则添加图像。 谢谢 :)
<?php
include('mysql.php');
if ($handle = opendir('images')) {
/* This is the correct way to loop over the directory. */
while (false !== ($file = readdir($handle))) {
if($file!='.' && $file!='..') {
$images[] = "('".$file."')";
}
}
closedir($handle);
}
$query = "INSERT INTO images (filename) VALUES ".implode(',', $images)." ";
if (!mysql_query($query)) {
print mysql_error();
}
else {
print "finished installing your images!";
}
?>
hey guys!
I have a script that should add images into the database. It does that. The only problem is that it does not only adds new images but also adds existing ones.
Im sure its a really simple task for you, for me its too much!
So again this code should check if an entry exists and then add the image if it does not exists.
Thank you :)
<?php
include('mysql.php');
if ($handle = opendir('images')) {
/* This is the correct way to loop over the directory. */
while (false !== ($file = readdir($handle))) {
if($file!='.' && $file!='..') {
$images[] = "('".$file."')";
}
}
closedir($handle);
}
$query = "INSERT INTO images (filename) VALUES ".implode(',', $images)." ";
if (!mysql_query($query)) {
print mysql_error();
}
else {
print "finished installing your images!";
}
?>
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您可以使
filename
字段唯一(CREATE UNIQUE INDEX filename_idx ON images (filename)
),然后只需将INSERT INTO images
替换为INSERT忽略图像
。作为额外的好处,您现在还可以为
filename
字段建立索引,这将加快filename
的SELECT
速度。You can make the
filename
field unique (CREATE UNIQUE INDEX filename_idx ON images (filename)
) then simply replaceINSERT INTO images
withINSERT IGNORE INTO images
.As an added bonus, you'll now also have the
filename
field indexed, which will speed upSELECT
s byfilename
.让我们来看看。要检查现有文件名是否已存储在数据库中,您必须执行以下操作:
PS:您应该需要您的 mysql.php 文件,没有它,你的脚本的其余部分将不起作用。
Let's see. To check if exiting filenames are already stored in the database you must do the following:
PS: You should require your mysql.php file, without it, the rest of your script won't work.
您应该将
文件名
添加为数据库中的唯一键。或者,您可以使用这个 php 脚本:
You should add
filename
as unique key in your database.Or, you could use this php script:
为什么不对文件执行 md5sum 并使用它来确保唯一性,然后执行选择以查看文件是否存在,如果不存在则插入并返回 id 作为批准状态,或者它是否已经存在现有记录的 ID。按文件名进行操作是可以的,除非几个人上传相同的文件但名称不同。这样做的缺点是,如果文件很大,那么需要花费一些资源来执行此操作。
Why not do an md5sum on the file, and use that for uniqueness, then do a select to see if the file is there, if it isn't insert if it it and return the id as the approve state, or if it already exists the id of the existing record. Doing it by filename is fine, unless, several people are uploading the same file but named differently. The downside to doing this is if the files are big, then it takes some of your resources to do this.