Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / programming

Dynamically Add File Upload Control and Insert Text File data to Database With jQuery and PHP

4.86/5 (4 votes)
9 Dec 2013CPOL2 min read 37.3K  
How to dynamically create file upload control and add text file data to SQL database

Introduction

In our websites, we often need to upload multiple files at a time. To add pure HTML controls (especially in MVC applications) from JavaScript code, we can effectively use jQuery functions. In this tip, I will explain how to dynamically create file upload control and add text file data to MY SQL database.

Using the Code

jQuery makes it really easy to access and dynamically modify the DOM. Here I want to allow file uploads in a form. I want it to start with 1 file upload option displayed, and then if the user clicks on a link, another one upload is displayed below that one.

To understand the jQuery feature of adding control on page at run time, we will consider file upload example. Suppose we have a file upload feature in the web application. The number of files that user could upload is not fixed hence, we cannot provide fix number of file upload controls. There is also the possibility that user might upload a single document hence, it is not logical to display many upload fields.

The solution could be what most sites adopt, to show single file upload at start and provide "upload another file" button. When user clicks on it, another file upload control gets added in our page.

Each text file is in the correct format, with each field starting a new line, and then each record separate with a comma. Download the latest JQuery library.

Database 

SQL
CREATE TABLE 
IF NOT EXISTS `tbl_textfile` 
(
`firstname` varchar(100) NULL,
`lastname` varchar(100) NULL
)

HTML Code

HTML
<form id="uploadform" 
method="post" enctype="multipart/form-data">
<form id="uploadform" method="post" 
enctype="multipart/form-data">
<p><a href="#" 
id="addupload">Add another upload control</a></p>
<div style="width:250px; height:auto; border:1px #000 solid; padding:10px;">
<label>Upload Text File:</label> <input type="file" 
name="file[]" class="imageupload">
<div id="display"></div>    
<input type="submit" value="submit" 
name="submit" id="submit">
 </div>    
</form>   </form>

JQuery Code

JavaScript
$(function(){
    $('#addupload').click(function(){
        var addControl = '<label>Upload Text File:</label>';
        addControl += ' <input type="file" 
        name="file[]" class="imageupload">';
        $('#display').before(addControl); 
    });
});

PHP Code

PHP
if(isset($_POST["submit"]))
{
$rec_count=0;
for($i=0;$i<=count($_FILES["file"]["name"])-1;$i++){
$filename=$_FILES["file"]["tmp_name"][$i];
$row = 1;
if (($handle = fopen($filename, "r")) !== FALSE) 
{
  while (($data = fgetcsv($handle, 1000, ",")) !== FALSE){
  $num = count($data);
  $row++;
  $first=$data[0];
             $second=$data[1];
            $query="INSERT INTO `tbl_textfile`(`firstname`, `lastname`) VALUES ('$first', '$second')";
             $rec_count=mysql_query($query);        
        }
           fclose($handle);
      }     
    }
    if($rec_count == 1)
    {
        echo "Success";    
    }
    else
    {
        echo 'Error';    
    }
} 

Points of Interest

This control hides the complexity of dynamically creating file input HTML controls, and removes any constraint regarding the presentation of the files which have been selected for upload. For more advanced developers, the source code of the MultiUpload control is available at vaaah and is commented in great detail.

Conclusion

In this post, I have demonstrated how to take advantage of the “dynamic file upload control” in websites so you can intuitively use your JQuery Object. This is the fastest way how to upload text file data to database using PHP with JQuery .

Live Demo 

http://www.vaaah.com

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)