【问题标题】:saving uniqid in database & picture folder在数据库和图片文件夹中保存 uniqid
【发布时间】:2014-03-07 08:00:12
【问题描述】:

我正在学习如何使用唯一 id 重命名上传的图片(或文件),使其与其他上传的文件不同;将其保存到数据库中,以便可以将其称为用户图像并将其保存在图像文件夹中。

我的问题是,我已经知道如何用唯一的文件名重命名和保存图像,但我不知道如何将唯一的文件名保存在数据库中,所以它调用了那个确切的图像。它似乎将“数组”保存到数据库而不是唯一的文件名。

如果有人对我如何纠正这个问题有任何想法,我将非常感谢学习经验哈哈:

<?php 

//This is the directory where images will be saved  

//This gets all the other information from the form 
$name=$_POST['name']; 
$email=$_POST['email']; 
$phone=$_POST['phone']; 
$pic=pathinfo($_FILES["photo"]["name"]);

// Connects to your Database 
mysql_connect("businessdb1.db.9878324.hostedresource.com", "user", "password") or die(mysql_error()) ; 
mysql_select_db("businessdb1") 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"],
   "avatars/" . uniqid() . '.' . $pic['extension'])) 
{ 

//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."; 
} 
?>

【问题讨论】:

  • 重命名后为什么不保存?
  • pathinfo() 返回一个数组
  • 尝试用var_dump($pic)探索$pic,它是一个关联数组,这就是你得到Array的原因。此外,此代码也不安全,因为您直接插入用户数据,更糟糕的是,您使用了已弃用的 mysql_* 函数。

标签: php mysql arrays database unique


【解决方案1】:

您可以简单地将生成的 id 保存在一个变量中,并在 INSERT INTO ...move_uploaded_file() 调用中使用。像这样的:

<?php
$name=$_POST['name']; 
// .... snip ....

// switched to mysqli_ for the example, save the resulting db link (should check for connection errors too)
$db = mysqli_connect( /* login credentials */);
// generate the uniqid and save it to a variable
$file_uniq_id = uniqid();

// then use the generated id here
if(move_uploaded_file($_FILES["photo"]["tmp_name"],
  "avatars/" . $file_uniq_id . '.' . $pic['extension'])) 
{ 

    mysqli_query($db, 'INSERT INTO `employees` VALUES (
    '.mysqli_query($db, $name).',
    '.mysqli_query($db, $email).',
    '.mysqli_query($db, $phone).',
    '.mysqli_query($db, $file_uniq_id).')'); // And here, you can add path or extension as you see fit
}

您的代码中也存在一些与功能无关的问题:

  1. 始终转义查询参数,否则您将遇到SQL injection 问题。
  2. 停止使用mysql_* 函数,因为它们是deprecatedmysqli_* 家族的工作方式几乎相同。

【讨论】:

  • 你所说的对我来说很有意义,但我似乎无法让代码工作大声笑。这个mysqli对我来说很新。老实说,我想要一个唯一的 id 让我自己更难做到这一点,这样人们就不会尝试上传具有相同扩展名的图片。我正在使用本教程:php.about.com/od/phpwithmysql/ss/Upload_file_sql.htm(由于另一个教程,将图像文件夹更改为头像)并且上传、保存在数据库中并调用正确的图像文件以显示用户信息,但我想添加唯一的 id,这就是它出错的地方哈哈。
  • 恐怕无法替代调试。使用error_reporting(E_ALL)ini_set('display_errors', 1) 打开错误消息,听听它能告诉你什么。你也可以放置var_dump()s 来查看变量,这样你就可以看到是什么(例如,转储 SQL 查询、将文件移动到的文件路径、if 中移动的返回值等等,直到你看到一些不正常的东西。想想每个应该是什么,然后检查它是否真的得到了你想象的值。
  • 好的,我会再玩一些。感谢您的所有时间和帮助!
猜你喜欢
  • 1970-01-01
  • 2014-12-11
  • 1970-01-01
  • 1970-01-01
  • 2020-03-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-12-20
相关资源
最近更新 更多