tuchawat tuchawat - 19 days ago 5
PHP Question

PHP - How can I insert the new filenames of uploading to MySQL

I'm doing the upload multimage files and rename it successfully.
However, I don't know, How to get the name of file that I rename it with function move_uploaded_file(). I want to get the newname to insert to mySQL

if(isset($_POST['submit']))
{

$count=count($_FILES["images"]["name"]);


for($i=0;$i<$count;$i++)
{
if ((($_FILES["images"]["type"][$i] == "image/gif")
|| ($_FILES["images"]["type"][$i] == "image/jpeg")
|| ($_FILES["images"]["type"][$i] == "image/png"))
&& ($_FILES["images"]["size"][$i] < 100000))
{

if ($_FILES["images"]["error"][$i] > 0)
{
echo "File Error : " . $_FILES["images"]["error"][$i] . "<br />";
}
else
{
// echo "Upload File Name: " . $_FILES["images"]["name"][$i] . "<br />";
// echo "File Type: " . $_FILES["images"]["type"][$i] . "<br />";
//echo "File Size: " . ($_FILES["images"]["size"][$i] / 1024) . " Kb<br />";

if (file_exists("images/location/".$_FILES["images"]["name"][$i] ))
{
echo "<b>".$_FILES["images"]["name"][$i] . " already exists. </b>";
}
else
{
move_uploaded_file($_FILES["images"]["tmp_name"][$i] ,"images/location/"."NEW_NAME!!!".$i.".jpg" );
// echo "Stored in: " . "images/location/" . $_FILES["images"]["name"][$i] ."<br />";
?>

<?php
}
}
}else
{
echo "Invalid file detail ::<br> file type ::".$_FILES["images"]["type"][$i] ." , file size::: ".$_FILES["images"]["size"][$i] ;
}
}
}


..

<form action = "" method="POST" enctype="multipart/form-data">
<input type="file" name="images[]" size="20" />
<input type="file" name="images[]" size="20" />
<input type="file" name="images[]" size="20" />
<input type="submit" name="submit"/>
</form>

Answer

I have used this in my project

$temp = explode(".", $_FILES['image']['name']);
$name = round(microtime(true)) . substr(md5(rand()), 0, 4) . '.' . end($temp);
move_uploaded_file($_FILES['image']['tmp_name'], $name);
//this is for single image upload
//Here $name is the new image name. You can then use your mysql_insert function to insert new image name to the database

//to upload multiple file just pass the file name as an array,tmp_name as an array
public function __attachments_upload($name, $tmp_name) {
    foreach ($name as $key => $value) {
        $temp = explode(".", $value);
        $name = round(microtime(true)) . substr(md5(rand()), 0, 4) . '.' . end($temp);
        move_uploaded_file($tmp_name[$key], $name);
        //here you can use mysql_insert 
    }
}