Saturday, July 14, 2012

Importing a deliminator-ed .txt or .csv file to MySQL DB, in PHP, directly from web form


Its a common & handy thing to import data, directly into database- by a Website Admin user. Its much more efficient process for the Admin to insert data into table. Else- its kinda boring and irritating procedure to insert into table from 'Add User Form' or Phpmyadmin or whatever. Import from File MySQL Sample Command
LOAD DATA LOCAL INFILE 'from_import_file'
REPLACE INTO TABLE `table_name`
FIELDS TERMINATED BY '||' 
LINES TERMINATED BY '\n' STARTING BY ''

Details from Scratch

At very first, we'll take the file from the user, using simple form. Then we'll use LOAD DATA INFILE to load into DB. Here is the code snippet-

1. Create a Temporary table which will have same field number as the imported DB file. For e.g- importUsers.txt content( file to be imported- with deliminated string || )
John Doe||user_id_123||The XYZ Company||Chicago
Mike Blinov||user_id_140||The ABC Company||New York
Austin Steven||user_457||WWE Tech LTD||Los Angeles
2. Then create the temporary table with exact 4 columns-
CREATE TABLE IF NOT EXISTS `users_temp` (
  `name` varchar(50) NOT NULL,
  `userId` varchar(50) NOT NULL,
  `company` varchar(50) NOT NULL,
  `city` varchar(50) NOT NULL
)
3. Have an HTML Form
<form enctype="multipart/form-data"  action="" method="post" >
            
    <label for="file_upload">Import Users</label>
    <input type="file" name="file_upload" id="file_upload" />
    
    <br/>
    
  <input type="submit" value="Import" />
</form>
4. On Submit Form PHP Code, upload the file with a unique name (This name is going to be used in the LOAD DATA Query) & getting the path of the uploaded file- from root
if (!empty($_FILES)) 
{
    $tempFile = $_FILES['file_upload']['tmp_name'];

    // Validate the file type
    $fileTypes = array('txt','csv','CSV'); // Valid File Extensions
    $fileParts = pathinfo($_FILES['file_upload']['name']);
    
    if (in_array($fileParts['extension'],$fileTypes))
    {
        //ploading with a unique name
        $uploadedFileName = 'import_users_'.time().'_'.rand(100,999999).'.'.$fileParts['extension'];
        $targetFile = 'ImportUser/' . $uploadedFileName;
        
        //File Uploaded
        move_uploaded_file($tempFile,$targetFile);
        
        // Getting the Full Path
        $fullPath = $_SERVER['SCRIPT_FILENAME'];
        $pathParts = pathinfo($fullPath);
        $pathToCurFile = $pathParts['dirname'];
        
        // Getting the Full path of uploaded file- FROM ROOT
        $uploadedFilepath = $pathToCurFile.'/'.$targetFile;
        
        // Function defined later
        $result  = importUsers($uploadedFilepath);
        
    } 
    else 
    {
        //Error
        echo 'Invalid file type. Please choose .txt or .csv file.';
    }
}
else
{
     //Error
     echo 'Please upload a user list file.';
}
5. Mysql Commned for import the file
function importUsers($filePathFromRoot)
{
 $sql = "LOAD DATA LOCAL INFILE '".$filePathFromRoot."'
                    REPLACE
                    INTO TABLE `users_temp`
                    FIELDS TERMINATED BY '||' 
     LINES TERMINATED BY '\n' STARTING BY ''";
                    
 $res = mysql_query($sql) or die ("Import Error");
}
6. Now after a successful import every-time, we can read from this temporary table and populate our actual table & then make this temporary table empty.
- thats all.
Please comment in case of any issue.

No comments:

Post a Comment