2

I have the following code to upload files to a database in mysql:

Index.php

<?php
include_once 'dbconfig.php';
?>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>File Uploading With PHP and MySql</title>
<link rel="stylesheet" href="style.css" type="text/css" />
</head>
<body>
<div id="header">
  <label>File Uploading With PHP and MySql</label>
</div>
<div id="body">
     <form action="upload.php" method="post" enctype="multipart/form-data">
  <input type="file" name="file" />
<button type="submit" name="btn-upload">upload</button>
</form>
<br /><br />

<?php
if(isset($_GET['success']))
{
    ?>
    <label>File Uploaded Successfully...  <a href="view.php">click here to view file.</a></label>
    <?php
}
else if(isset($_GET['fail']))
{
    ?>
    <label>Problem While File Uploading !</label>
    <?php
}
else
{
    ?>

    <?php
}
?>

Upload.php

<?php
include_once 'dbconfig.php';
if(isset($_POST['btn-upload']))
{    

$file = rand(1000,100000)."-".$_FILES['file']['name'];
$file_loc = $_FILES['file']['tmp_name'];
$file_size = $_FILES['file']['size'];
$file_type = $_FILES['file']['type'];
$folder="uploads/";

// new file size in KB
$new_size = $file_size/1024;  
// new file size in KB

// make file name in lower case
$new_file_name = strtolower($file);
// make file name in lower case

$final_file=str_replace(' ','-',$new_file_name);

if(move_uploaded_file($file_loc,$folder.$final_file))
{
    $sql="INSERT INTO tbl_uploads(file,type,size) VALUES('$final_file','$file_type','$new_size')";
    mysql_query($sql);
    ?>
    <script>
    alert('successfully uploaded');
    window.location.href='index.php?success';
    </script>
    <?php
}
else
{
    ?>
    <script>
    alert('error while uploading file');
    window.location.href='index.php?fail';
    </script>
    <?php
}
}
?>

which works well, but only for individual file. I saw many tutorials, but I can not modify the code to allow upload multiple files at once. Any suggestions?

1

1 Answer 1

1

To allow multiple file uplodes you need to set attribute multiple="multiple" on the file input with a name file[]. Or you can use separate inputs with a name file[] as well. Than to store values in database make a

 foreach($_FILES['filename']['name'] as $key=>$name){
     // store each file and write data to DB for each file
     //for example to get the name of file
     $name = $_FILES['filename']['name'][$key];
 }
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.