Hope you are using this package maat Excell it makes work a bit easier for a start.
Jan 20, 2016
3
Level 5
import file from excel to mySql using laravel
I need to upload Excel values in database field.My Excel file has two values first value :list of pin numbers second value : list of cost
my database table hasid,pin_numbers and cost column . I need to store excel row values to database column pin_number and cost
How can i do this?
my current code is like this
if(Input::hasFile('file'))
{
$f = Input::file('file');
$att = new Attachment;
$att->name = $f->getClientOriginalName();
//how to save Excel pin_number and cost to mysql column pin_number and cost
$att->save();
return Redirect::to('/upload_form');
}
my db table is like this
CREATE TABLE `attachments` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`pin_number` varchar(255) DEFAULT NULL,
`cost` varchar(255) DEFAULT NULL,
`name` varchar(255) NOT NULL,
`created_at` datetime NOT NULL,
`updated_at` datetime DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB;
In PHP i used to do like this
<?php
include 'db.php';
if(isset($_POST["Import"])){
echo $filename=$_FILES["file"]["tmp_name"];
if($_FILES["file"]["size"] > 0)
{
$file = fopen($filename, "r");
while (($emapData = fgetcsv($file, 10000, ",")) !== FALSE)
{
//It wiil insert a row to our subject table from our csv file`
$sql = "INSERT into subject (`SUBJ_CODE`, `SUBJ_DESCRIPTION`, `UNIT`, `PRE_REQUISITE`,COURSE_ID, `AY`, `SEMESTER`)
values('$emapData[1]','$emapData[2]','$emapData[3]','$emapData[4]','$emapData[5]','$emapData[6]','$emapData[7]')";
//we are using mysql_query function. it returns a resource on true else False on error
$result = mysql_query( $sql, $conn );
if(! $result )
{
echo "<script type=\"text/javascript\">
alert(\"Invalid File:Please Upload CSV File.\");
window.location = \"index.php\"
</script>";
}
}
fclose($file);
//throws a message if data successfully imported to mysql database from excel file
echo "<script type=\"text/javascript\">
alert(\"CSV File has been successfully Imported.\");
window.location = \"index.php\"
</script>";
//close of connection
mysql_close($conn);
}
}
?>
Please help me to make a modification in laravel5
Please or to participate in this conversation.