Ibad Shah Ibad Shah - 23 days ago 35
MySQL Question

Upload Multiple Files in PHP & INSERT path to MySQL

I've setup a form to upload multiple files from a PHP script and then insert it into the Database with path. Here's my code

<form action="" method="post" enctype="multipart/form-data">
<tr class='first'>
<td>Property Image : </td>
<input type="file" name="pic_upload[]" >
<input type="file" name="pic_upload[]" >
<input type="file" name="pic_upload[]" >
<tr class='first'>
<td>&nbsp;</td><td><input type="submit" name="create" value="Add" /></td>
if(isset($_POST['create'])) {
$path = "images/";
for ($i=0; $i<count($_FILES['pic_upload']['name']); $i++) {
$ext = explode('.', basename( $_FILES['pic_upload']['name'][$i]));
$path = $path . md5(uniqid()) . "." . $ext[count($ext)-1];
move_uploaded_file($_FILES['pic_upload']['tmp_name'][$i], $path);
$sql = "INSERT INTO post (`image`) VALUES ('$path');";
$res = mysqli_query($con,$sql) or die("<p>Query Error".mysqli_error()."</p>");
echo "<p>Post Created $date</p>";

The Script runs successfully, but at the database end inside the column it looks like this.


Help me out with this please

Answer Source

Move $path = "images/"; inside the for loop. Otherwise you are appending to the filename without resetting it after each iteration. Actually, you don't need to use a variable for that prefix at all. You can simply write 'images/' . md5(uniqid()) . "." . $ext[count($ext)-1] immediately.

To write the values to the database, you can either run the query in each iteration as well or add the paths to an array which is transformed to the comma-separated insertion list according to the SQL syntax.