Upload and insert xls file to mysql? - php

I´m strugeling to find a tutorial to show me how to code a php script that will let me upload and insert xls (not CSV) into mysql. I have this php script with fgetcsv and it works all fine. But i need to include support for xls.
my 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 excell_import (`objekt`, `element_nummer`, `element_hojd`, `element_langd`,COURSE_ID, `AY`, `SEMESTER`)
values('$emapData[1]','$emapData[2]','$emapData[3]','$emapData[4]','$emapData[5]','$emapData[6]','$em apData[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);
}
?>

Working script for collect data from xls file and insert to mysql.
<?php
//include the following 2 files for phpexcel
require 'Classes/PHPExcel.php';
require_once 'Classes/PHPExcel/IOFactory.php';
//Establish connection to mysql
$conn=mysql_connect($host,$username,$password) or die("Could not connect");
mysql_select_db($dbname,$conn) or die("could not connect database");
//Load file
$path = "atbl.xls";
$objPHPExcel = PHPExcel_IOFactory::load($path);
//Loop threw file to get data
foreach ($objPHPExcel->getWorksheetIterator() as $worksheet) {
$worksheetTitle = $worksheet->getTitle();
$highestRow = 20; //$worksheet->getHighestRow(); // e.g. 10
$highestColumn = 'G'; //worksheet->getHighestColumn(''); // e.g 'F'
$highestColumnIndex = PHPExcel_Cell::columnIndexFromString($highestColumn);
$nrColumns = ord($highestColumn) - 64;
echo "<br>The worksheet ".$worksheetTitle." has ";
echo $nrColumns . ' columns (A-' . $highestColumn . ') ';
echo ' and ' . $highestRow . ' row.';
echo '<br>Data: <table border="1"><tr>';
for ($row = 11; $row <= $highestRow; ++ $row) {
echo '<tr>';
for ($col = 0; $col < $highestColumnIndex; ++ $col) {
$cell = $worksheet->getCellByColumnAndRow($col, $row);
$val = $cell->getCalculatedValue();
//$dataType = PHPExcel_Cell_DataType::dataTypeForValue($val);
echo '<td>' . $val . '<br></td>';
}
echo '</tr>';
}
echo '</table>';
}
for ($row = 11; $row <= $highestRow; ++ $row) {
$val=array();
for ($col = 0; $col < $highestColumnIndex; ++ $col) {
$cell = $worksheet->getCellByColumnAndRow($col, $row);
$val[] = $cell->getValue();
}
//Insert data from file to mysql
$sql="INSERT INTO phpexcel(objekt_nr, objekt_rev, element_nr, element_langd, element_bredd, element_hojd)
VALUES ('".$val[1] . "','" . $val[2] . "','" . $val[3]. "','" . $val[4]. "','" . $val[5]. "','" . $val[6]. "')";
//echo $sql."\n";
mysql_query($sql) or die('Invalid query: ' . mysql_error());
}
?>

Related

How to Validate Employee Id in Importing File in .CSV format to SQL?

How to Validate Employee Id in Importing File in .CSV format to SQL?
*a code that check if the data is already exist.
-->sample: if the Employee Id already exist it promts "Employee ID already Exist"..
if the rows in csv, you can make a array of csv rows.
$list =array();
$id = array();
while( ($rows= getcsv($hande)) !== false)
{
array_push($list, $rows);
array_push($id, $rows['emplyee_id']);
}
then check mysql or database
$check_id = implode(",", $id);
$que = "select employ_id from table where employ_id in ($check_id)";
at this time you can find employ_ids from database.
if you make employee_id column unique, your code would be like this
$result=mysqli_query($db_con", "insert into table (employ_id) values ('$empoy_id')";
if($result == false) // if employ_id alreay exists in table $result is false
{
}
but as i know, the best way using index is checking key is exists before inserting data not after inserting query failed.
This is my code:
`<?php
if ($_FILES["file"]["error"] > 0)
{
echo "Error: " . $_FILES["file"]["error"] . "<br>";
}
else
{
echo "Upload: " . $_FILES["file"]["name"] . "<br>";
echo "Type: " . $_FILES["file"]["type"] . "<br>";
echo "Size: " . ($_FILES["file"]["size"] / 1024) . " Kb<br>";
echo "Stored in: " . $_FILES["file"]["tmp_name"];
$a=$_FILES["file"]["tmp_name"];
echo $a;
$connect = mysql_connect('localhost','root','');
if (!$connect) {
die('Could not connect to MySQL: ' . mysql_error());
}
//your database name
$cid =mysql_select_db('cgi_warehouse',$connect);
// path where your CSV file is located
//define('CSV_PATH','C:/xampp/htdocs/');
//<!-- C:\\xampp\\htdocs -->
// Name of your CSV file
$csv_file = $a;
if (($getfile = fopen($csv_file, "r")) !== FALSE) {
$data = fgetcsv($getfile, 1000, ",");
while (($data = fgetcsv($getfile, 1000, ",")) !== FALSE) {
//$num = count($data);
//echo $num;
//for ($c=0; $c < $num; $c++) {
$result = $data;
$str = implode(",", $result);
$slice = explode(",", $str);
$col1 = $slice[0];
$col2 = $slice[1];
$col3 = $slice[2];
$col4 = $slice[3];
$col5 = $slice[4];
$col6 = $slice[5];
$col7 = $slice[6];
$col8 = $slice[7];
$col9 = $slice[8];
$col10 = $slice[9];
$col11 = $slice[10];
$col12 = $slice[11];
$col13 = $slice[12];
$col14 = $slice[13];
$col15 = $slice[14];
$col16 = $slice[15];
$query = "INSERT INTO tools(tools_id, item_description, category_id, sn, qty, price, supplier, frm, location, ref_no, sender, receiver, date_receive, date_added, status, remarks) VALUES('".$col1."','".$col2."','".$col3."','".$col4."','".$col5."','".$col6."','".$col7."','".$col8."','".$col9."','".$col10."','".$col11."','".$col12."','".$col13."','".$col14."','".$col15."','".$col16."')";
$s=mysql_query($query, $connect );
}
}
echo "<script>alert('Record successfully uploaded.');window.location.href='#';</script>";
mysql_close($connect);
}
?>`

PHPExcel upload data via xls file

Do you know what I am doing wrong here? What I try to do is select a value from a choice box and then upload a xls file when I click on submit it uploads it into MySQL. But when I click on submit I get Invalid post request.
require '../PHPExcel/Classes/PHPExcel.php';
require_once '../PHPExcel/Classes/PHPExcel/IOFactory.php';
$proposal = "select * from proposal";
$rsExport = mysqli_query($DBCONN, $proposal) or die(mysql_error());
echo '<form id="proposal_form" method="post">';
echo "<select id='select_your_proposal' name = 'select_your_proposal'>";
echo "<option value=''>Select Your Proposal</option>";
while ($row = mysqli_fetch_array($rsExport)) {
echo "<option value='" . $row['id'] . "'>" . $row['enterpriseid'] . " - " . $row['sitename'] . " - " . $row['presaleconsultant'] . " </option>";
}
echo "</select>";
?>
<br>
<form method="post" enctype="multipart/form-data">
1.) Upload User File: <input type="file" name="spreadsheet"/>
<br>
<br>
<?php
if (isset($_POST['select_your_proposal'])) {
$proposal2 = mysqli_query($DBCONN, "select * from proposal where id = '" . $_POST['select_your_proposal'] . "'");
$row = $proposal2->fetch_assoc();
$proposalid = $_POST['select_your_proposal'];
unset($sessionid);
$sessionid = uniqid();
$user = CurrentUserName();
$date = date('Y-m-d H:i:s');
ini_set('display_errors', 1);
// Check valid spreadsheet has been uploaded
if (isset($_FILES['spreadsheet'])) {
if ($_FILES['spreadsheet']['tmp_name']) {
if (!$_FILES['spreadsheet']['error']) {
$inputFile = $_FILES['spreadsheet']['tmp_name'];
$extension = strtoupper(pathinfo($inputFile, PATHINFO_EXTENSION));
if ($extension == 'XLSX' || $extension == 'XLS') {
$objPHPExcel = PHPExcel_IOFactory::load($inputFile);
foreach($objPHPExcel->getWorksheetIterator() as $worksheet) {
$worksheetTitle = $worksheet->getTitle();
$highestRow = $worksheet->getHighestRow(); // e.g. 10
$highestColumn = $worksheet->getHighestColumn(); // e.g 'F'
$highestColumnIndex = PHPExcel_Cell::columnIndexFromString($highestColumn);
$nrColumns = ord($highestColumn) - 64;
echo "<br>The worksheet " . $worksheetTitle . " has ";
echo $nrColumns . ' columns (A-' . $highestColumn . ') ';
echo ' and ' . $highestRow . ' row.';
echo '<br>Data: <table border="1"><tr>';
for ($row = 1; $row <= $highestRow; ++$row) {
echo '<tr>';
for ($col = 0; $col < $highestColumnIndex; ++$col) {
$cell = $worksheet->getCellByColumnAndRow($col, $row);
$val = $cell->getValue();
$dataType = PHPExcel_Cell_DataType::dataTypeForValue($val);
echo '<td>' . $val;
}
echo '</tr>';
}
echo '</table>';
}
for ($row = 2; $row <= $highestRow; ++$row) {
$val = array();
for ($col = 0; $col < $highestColumnIndex; ++$col) {
$cell = $worksheet->getCellByColumnAndRow($col, $row);
$val[] = $cell->getValue();
}
$sqlsession = "INSERT IGNORE INTO session (
xxxx
";
$sqluser = "INSERT INTO bw_users (
xxxx
);";
// echo $sqluser."\n";
// echo $sqlsession."\n";
$result = mysqli_query($DBCONN, $sqlsession);
$result = mysqli_query($DBCONN, $sqluser);
if (!$result) {
echo "DB Error, could not query the database\n";
echo 'MySQL Error: ' . mysql_error();
exit;
}
}
}
}
}
}
else {
echo "Please upload an XLSX or XLS file";
}
}
echo "<br>";
echo "</form>";
echo '<input type="submit" name="submit" value="Submit">';
?>
You need to define action in the form your code should look like dis
<form method="post" enctype="multipart/form-data" action="yournextpage.php">
1.) Upload User File: <input type="file" name="spreadsheet"/>
Or use some javascript to redirect the page

Import CSV file data into MySQL table [duplicate]

This question already has answers here:
Insert and update CSV file data into MySQL table using PHP
(2 answers)
Closed 7 years ago.
I am inserting record from CSV file to MySQL table; if any record already exists update that record and insert other records and if there is no match of the record insert all records.
Here is my code
<?php
$connect = mysql_connect('localhost','root','root');
if (!$connect) {
die('Could not connect to MySQL: ' . mysql_error());
}
$cid =mysql_select_db('bizin490_devcredit',$connect);
define('CSV_PATH', '/home/ubc/Documents/');
$csv_file = CSV_PATH . "test.csv";
$csvfile = fopen($csv_file, 'r');
$theData = fgets($csvfile);
$i = 0;
while (!feof($csvfile)) {
$csv_data[] = fgets($csvfile, 1024);
$csv_array = explode(",", $csv_data[$i]);
$insert_csv = array();
$insert_csv['name'] = $csv_array[0];
$insert_csv['email'] = $csv_array[1];
$query = mysql_query("select name from test where name='" . $insert_csv['name'] . "'");
$count = mysql_num_rows($query);
if ($count == 0) {
$query = "INSERT INTO test(name,email)VALUES('" . $insert_csv['name'] . "','" . $insert_csv['email'] . "')";
$n = mysql_query($query, $connect);
} else {
$sql = "update test set email='".$insert_csv['email']."'";
//echo "<pre>";print_r($sql);
$qu = mysql_query($sql);
echo "<pre>";print_r($_POST);
}
$i++;
//die;
}
fclose($csvfile);
echo "File data successfully imported to database!!";
mysql_close($connect);
?>
Something like:
LOAD DATA INFILE '/home/ubc/Documents/test.csv'
REPLACE
INTO TABLE `test`
(name, email)

difference between localhost(wamp) and host on phpExcel library No data received error

I read some data from a xls file with phpExcel library with this code:
$fisierInbound = "inbound.xls";
callsInbound();
function callsInbound() {
global $fisierInbound;
global $current;
global $con;
$identify = PHPExcel_IOFactory::identify('daily/' . $fisierInbound);
$objReader = PHPExcel_IOFactory::createReader($identify);
$objReader->setReadDataOnly(true);
$objPHPExcel = $objReader->load('daily/' . $fisierInbound);
$objWorksheet = $objPHPExcel->setActiveSheetIndex(0);
//$objWorksheet = $objPHPExcel->getActiveSheet();
$query = mysqli_query($con, "SELECT * FROM users WHERE tip_user='agent' AND NOT (departament='online')");
while($usr = mysqli_fetch_array($query)) {
$data[] = $usr;
}
foreach ($objPHPExcel->getWorksheetIterator() as $worksheet) {
$worksheetTitle = $worksheet->getTitle();
$highestRow = $worksheet->getHighestRow(); // e.g. 10
$highestColumn = $worksheet->getHighestColumn(); // e.g 'F'
$highestColumnIndex = PHPExcel_Cell::columnIndexFromString($highestColumn);
$dataCalls = $worksheet->getCellByColumnAndRow(2, 2)->getValue();
$dataSubstr = substr($dataCalls, 53);
echo $dataSubstr;
foreach ($data as $db) {
for ($row = 6; $row <= $highestRow; ++ $row) {
$marca = $worksheet->getCellByColumnAndRow(3, $row)->getValue();
$nr = $worksheet->getCellByColumnAndRow(4, $row)->getValue();
if($db['marca'] == $marca) {
mysqli_query($con, "INSERT INTO dailycalls(data, nr, departament, oras, tip, id_user)
VALUES('$dataSubstr', '$nr', '" . $db['departament'] . "', '" . $db['oras'] . "', 'inbound', '" . $db['id'] . "')");
}
}
}
}
}
It works perfect on localhost but if I run it from host I get Chrome error No data received
Unable to load the webpage because the server sent no data.
Error code: ERR_EMPTY_RESPONSE
but the query runs(the data is inserted into the db). What seems to be the problem ?
Thanks!

PHPExcel - Getting irrelevant value in MySQL

Whenever I import an excel file into MySQL using PHPExcel then I don't get some values and also values get inserted into irrespective columns.
BUT when I use echo for showing excel file then it shows exact report.
Also, I want only few selected columns to be imported from 10-15 columns.
Thanks in advance
My Code
<?php
//include the following 2 files
require 'C:\xampp\PHPExcel_1.7.9_doc\Classes\PHPExcel.php';
require_once 'C:\xampp\PHPExcel_1.7.9_doc\Classes\PHPExcel\IOFactory.php';
$conn = mysql_connect("localhost","root","");
mysql_select_db("invoice",$conn);
$file=$_POST['file'];
$srow=$_POST['srow'];
$objPHPExcel = PHPExcel_IOFactory::load($file);
foreach ($objPHPExcel->getWorksheetIterator() as $worksheet) {
$worksheetTitle = $worksheet->getTitle();
$highestRow = $worksheet->getHighestRow(); // e.g. 10
$highestColumn = $worksheet->getHighestColumn(); // e.g 'F'
$highestColumnIndex = PHPExcel_Cell::columnIndexFromString($highestColumn);
$nrColumns = ord($highestColumn) - 64;
echo "<br>The worksheet ".$worksheetTitle." has ";
echo $nrColumns . ' columns (A-' . $highestColumn . ') ';
echo ' and ' . $highestRow . ' row.';
}
echo 'Data: <table width="100%" cellpadding="3" cellspacing="0"><tr>';
for ($row = $srow; $row <= $highestRow-1; ++ $row) {
echo '<tr>';
for ($col = 0; $col < $highestColumnIndex; ++ $col) {
$cell = $worksheet->getCellByColumnAndRow($col, $row);
$val = $cell->getValue();
if($row === 1)
echo '<td style="background:#000; color:#fff;">' . $val . '</td>';
else
echo '<td>' . $val . '</td>';
}
echo '</tr>';
}
echo '</table>';
for ($row = $srow; $row <= $highestRow; ++ $row) {
$val=array();
for ($col = 0; $col <= $highestColumnIndex; ++ $col) {
$cell = $worksheet->getCellByColumnAndRow($col, $srow);
$val[] = $cell->getValue();
}
$dropdownval=$_POST['menu'];
if ($dropdownval!='none')
{
$sql="INSERT INTO $dropdownval(`Bkng Date`,`ID Number`,`Pax Name`,`Ticket Number`,`PNR`,`Sector`,`Travel Date`,`Basic`,`Tax`,`Net Payable`)
VALUES('".$val[1]."','".$val[2]."','".$val[3]."','" .$val[4]."','".$val[5]."','".$val[6]."','".$val[7]."','".$val[8]."','".$val[9]."','".$val[10]."')";
mysql_query($sql)or die('Invalid query: ' . mysql_error());
if(mysql_query($sql))
echo "Successfully Uploaded ".$file;
else
echo "Error while uploading ".$file;
//echo $sql."\n";
}
else
{
$tname=$_POST['tname'];
$createTable="CREATE TABLE $tname(
`Bkng Date` DATE NOT NULL ,
`ID Number` INT NOT NULL ,
`Pax Name` VARCHAR( 100 ) NOT NULL ,
`Ticket Number` VARCHAR( 100 ) NOT NULL ,
`PNR` VARCHAR( 50 ) NOT NULL ,
`Sector` VARCHAR( 50 ) NOT NULL ,
`Travel Date` DATE NOT NULL ,
`Basic` DECIMAL NOT NULL ,
`Tax` DECIMAL NOT NULL ,
`Net Payable` DECIMAL NOT NULL)";
mysql_query($createTable);
$sql1="INSERT INTO $tname(`Bkng Date`,`ID Number`,`Pax Name`,`Ticket Number`,`PNR`,`Sector`,`Travel Date`,`Basic`,`Tax`,`Net Payable`)
VALUES('".$val[1]."','".$val[2]."','".$val[3]."','" .$val[4]."','".$val[5]."','".$val[6]."','".$val[7]."','".$val[8]."','".$val[9]."','".$val[10]."')";
mysql_query($sql1)or die('Invalid query: ' . mysql_error());
if(mysql_query($sql1))
echo "Table $tname has been created...Successfully Uploaded ".$file;
else
echo "Error while uploading ".$file;
}
}
?>

Categories