我正在学习如何使用唯一ID重命名上传的图片(或文件),因此它与其他上传的文件不同;将其保存到数据库,以便可以将其作为用户的图像调用并将其保存在图像文件夹中。
我的问题是,我已经找到了如何使用唯一的文件名重命名和保存图像,但我不知道如何获取该唯一文件名以保存在数据库中,因此它会调用该图像。它似乎在拯救' Array'到数据库而不是唯一的文件名。
如果有人有任何想法我可以纠正这个问题,我非常感谢学习经历哈哈:
<?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.";
}
?>
答案 0 :(得分:0)
您只需将生成的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
}
您的代码中也存在一些与功能无关的问题:
mysql_*
函数,因为它们是deprecated。 mysqli_*
家庭的工作方式几乎相同。