Pergunta

I'm learning how to rename an uploaded picture (or file) with a unique id so it's not the same as other uploaded files; save it to a database so it can be called as a user's image and save it in the image folder.

My issue, is I have figured out how to rename and save the image with a unique file name but I have no idea how to get that unique filename to save in the database so it calls that exact image. It seems to be saving 'Array' to the database and not the unique filename.

If anyone has any ideas how I can correct this, I would very much appreciate the learning experience haha:

<?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."; 
} 
?>
Foi útil?

Solução

You can just simply save the generated id in a variable and use in in both the INSERT INTO ... and the move_uploaded_file() call. Something like this:

<?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
}

There are some non-functionality related problems in your code too:

  1. Always escape your query parameters, or you will have SQL injection issues.
  2. Stop using the mysql_* functions since they are deprecated. The mysqli_* family works almost the same.
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top