php - 如何检查文件的数据是否已经在数据库中

标签 php mysql database

我目前遇到一个问题,如果我多次运行此 php,那么一旦我当前在数据库中的图像数据将重复。例如,我将 5 张图片上传到我的上传文件,然后单击脚本,一切正常。当我添加另一张图片并再次单击脚本时,我的数据库中有 6 张图片变成了 11 张。我想知道如何修改我的代码才能解决这个问题。

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);
}

/* insert new record into the table images with the filename */
$query = "INSERT INTO images (filename) VALUES ".implode(',', $images)." ";
if (!mysql_query($query)) {
    print mysql_error();
}
else {
    print "finished installing your images!";
}

最佳答案

您可以将“文件名”列设为唯一键并使用INSERT IGNORE

有关插入忽略的更多信息:http://dev.mysql.com/doc/refman/5.5/en/insert.html

关于php - 如何检查文件的数据是否已经在数据库中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18393957/

相关文章:

PHPMailer - 如何在 altbody 中添加断行?

php - 使用 codeigniter php 加载多个 View

Swift Realm 将预取对象保存到新对象中

PHP MYSQL 模块未在 Amazon EC2 Bitnami AMI 中加载

php - 更新数据库表中所有行的 1 列

sql - 数据库可选参数错误

MySQL:LAST_INSERT_ID() 返回 0

php - 为什么这些相对路径在 php 中不起作用

php - 有效检查文档是否有子项

php - 在一个 API 请求中包含多个联接的单个查询,还是在单独的 API 请求中包含一些联接的几个查询?