php - 将更改后的文件名存储到 mysql 字段中

标签 php mysql file-upload

我有一个表单,用户可以在其中上传图像,并且这些图像保存在服务器中的特定文件夹中。同时,照片的文件名存储在 MySQL 表的特定字段中。

我尝试通过添加时间戳来更改文件名(并且它有效),但是这个新文件名不是存储在 MySQL 字段中的文件名,这意味着它存储来自用户的原始照片文件名。

有没有一种方法可以让新文件名存储在 MySQL 表中。

下面是我正在使用的代码:

enter code here

//This is the directory where images will be saved 
 $target = "pics/"; 
 $target = $target. basename( $_FILES['photo']['name']); 
 
 
 //This gets all the other information from the form 
 $name=$_POST['name']; 
 $email=$_POST['email']; 
 $phone=$_POST['phone']; 
 $pic=($_FILES['photo']['name']); 
 
 // Connects to your Database 
 mysql_connect("localhost", "username", "password") or die(mysql_error()) ; 
 mysql_select_db("test") or die(mysql_error()) ; 
 
 //Writes the information to the database 
 mysql_query("INSERT INTO `employees` VALUES ('$name', '$email', '$phone', '$pic')") ; 
 
 //Writes the photo to the server 
 if(move_uploaded_file($_FILES['photo']['tmp_name'], $target)) 
 { 
 
 //Tells you if its all ok 
 echo "The file ". basename( $_FILES['uploadedfile']['name']). " has been uploaded, and your information has been added to the directory"; 
 } 
 else { 
 
 //Gives and error if its not 
 echo "Sorry, there was a problem uploading your file."; 
 } 
 ?> 

我希望将文件重命名为唯一的文件名,并且希望将该唯一的文件名存储在 SQL 表的照片字段中。

最佳答案

插入之前,将新文件名保存到变量中,然后更改名称,最后将新名称插入数据库。

或者,如果您想在完成插入后更改名称,请在表上运行 UPDATE 查询,在其中更新文件名: UPDATE 表 SET 文件名 = 'new_filename' WHERE 文件名 = 'old_filename"

关于php - 将更改后的文件名存储到 mysql 字段中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6908578/

相关文章:

mysql - 如何从 SQL 中的 SUM() 子查询获取 MAX()

ruby-on-rails - 处理版本时如何跳过载波存储回调

java - Jersey 2 分段上传客户端

php 操作干扰 css

php - Symfony 2 实体字段属性

mysql - 具有 Null 值的多个 MySQL 列的 UNIQUE 约束

javascript - jQuery 表单在 IE 中的文件输入更改时自动提交

php - 验证数组中发送的复选框

php - 如何在 php bootstrap 模式中使用依赖下拉列表?

mysql - 如何正确禁用 MariaDB 的 InnoDB 全文停用词?