Anonymous
02 Feb, 2018

Is There An Easy Way To Upload Excel Data Directly To The Database?

1 Answer         3219 Views

Admin
02 Feb, 2018

Laravel Excel is quite helpful is resolving that one but we've got easy file handling php functions that can do the work with much convenience. Let's have a look at it.

 
public function importExcel()
{ 
    $file = $_FILES['uploads']['tmp_name']; 
    $handle = fopen($file, "r"); 

    while($filesop = fgetcsv($handle, 1000, ",")){ 
        $name = $filesop[0]; 
        $gender = $filesop[1]; 
        $address = $filesop[2]; 
        $age = $filesop[3]; 
        $education = $filesop[4]; 
        $contact = $filesop[5]; 

        DB::table('visitors')->insert([ 
            'name'=>$name, 
            'age'=>$age, 
            'gender'=>$gender, 
            'address'=>$address, 
            'education'=>$education, 
            'contact'=>$contact, 
        ]); 
    } 
} 

At first, we retrieved the file from the temporary location and we opened it in reading mode.

Using the while loop, we stored the values from the excelsheet rows as indexed arrays to some variables.

Finally, we added those variables in the insert query and executed while remaining inside the loop. That makes the function run until the last row of excelsheet and insert each of those rows individually in database.

Once completed, you can store a success message in session and display it to the user while redirecting the user.


198 Likes         0 Dislike         1 Comment        


Guest

22 May, 2022

It would be better if you explain about the parameters also.

Jiwan Thapa

20 Aug, 2022

There's no new things in this code to explain for an intermediate. $file stores the csv file uploaded while $handle checks if the file can be opened to read. If the file opens, then we take the file with php function fgetcsv,where we define the length higher than the the longest line in the csv file, and the separator in csv is always ",". Then, its all about running the loop until the last data from the csv file is inserted into our database. Hope, this helps.

Reply



Leave a comment