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;
}
}
?>
Related
I have an html-form to read out data from a DB that are then dislayed in an html-table. Columns that contain no values should not be displayed. This works well with the following code using array_column and array_filter:
$sql = "SELECT DISTINCT $selection FROM $table WHERE $where";
$result = mysqli_query($db, $sql) or die("<b>No results</b>"); //Running the query and storing it in result
$numrows = mysqli_num_rows($result); // gets number of rows in result table
$numcols = mysqli_num_fields($result); // gets number of columns in result table
$field = mysqli_fetch_fields($result); // gets the column names from the result table
$custom_column_arr = array('Color' => 'color_comment', 'Weight' => 'weight_comment');
if($numrows > 0) {
echo "<table id='myTable'>";
echo "<thead>";
$results = array();
while($row = mysqli_fetch_assoc($result)) {
$results[] = $row;
}
echo "<tr>";
echo "<th>" . 'Nr' . "</th>";
for($x = 0; $x < $numcols; $x++) {
$column[$x] = array_column($results, $field[$x]->name); // puts all existing values of a column into the field-name
if(array_filter($column[$x])) { // displays only those columns with at least one value in it
$key = array_search($field[$x]->name, $custom_column_arr);
if($key !== FALSE) {
echo "<th>" . $key . "</th>";
} else {
echo "<th>" . $field[$x]->name . "</th>";
}
}
}
echo "</tr></thead>";
echo "<tbody>";
$nr = 1;
$result = mysqli_query($db, $sql);
while($row = mysqli_fetch_array($result)) {
echo "<tr>";
echo "<td>" . $nr . "</td>";
for($k = 0; $k < $numcols; $k++) { // goes around until there are no columns left
$column[$k] = array_column($results, $field[$k]->name); // puts all existing values of a column into the field-name
if(array_filter($column[$k])) { // displays only those columns with at least one value in it
echo "<td>" . $row[$field[$k]->name] . "</td>"; //Prints the data } } echo "</tr>"; $nr = $nr + 1;
} // End of while-loop
echo "</tbody></table>";
}
}
mysqli_close($db);
}
Due to security reasons, I switched to PDO prepared statements to avoid SQL-injection:
enter code here
$sql = "SELECT DISTINCT $selection FROM $table WHERE color = :color AND weight = :weight";
$stmt = $pdo->prepare($sql);
$renalstatus = '10';
$bindValue = implode("/n ", $bindValue);
$stmt->bindValue(':color', $color, PDO::PARAM_STR);
$stmt->bindValue(':weight', $weight, PDO::PARAM_INT);
$stmt->execute();
$zeilen = $stmt->rowCount();
$spalten = $stmt->columnCount();
if($zeilen > 0) {
echo "<table id='myTable'>";
echo "<thead>";
$results = array();
while($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
$results[] = $row;
}
echo "<tr>";
echo "<th>" . 'Nr' . "</th>";
for($x = 0; $x < $spalten; $x++) {
$column[$x] = array_column($results, $fields[$x]->name); // puts all existing values of a column into the field-name
if(array_filter($column[$x])) { // displays only those columns with at least one value in it
$key = array_search($fields[$x], $custom_column_arr);
if($key !== FALSE) {
echo "<th>" . $key . "</th>";
} else {
echo "<th>" . $fields[$x] . "</th>";
}
}
}
echo "</tr></thead>";
echo "<tbody>";
$nr = 1;
$stmt = $pdo->query($sql);
while($row = $stmt->fetch(PDO::FETCH_NUM)) {
echo "<tr>";
echo "<td>" . $nr . "</td>";
for($k = 0; $k < $spalten; $k++) { // goes around until there are no columns left
$column[$k] = array_column($results, $fields[$k]->name); // puts all existing values of a column into the field-name
if(array_filter($column[$k])) { // displays only those columns with at least one value in it
echo "<td>" . $row[$k] . "</td>"; //Prints the data}
}
echo "</tr>";
$nr = $nr + 1;
} // End of while-loop
echo "</tbody></table>";
}
}
$stmt->close();
The query results are correctly displayed as before. However, completely empty columns are displayed as well and shoul be hidden.
After having built the headline, in mysqli there is a second query before the rows are generated:
$result = mysqli_query($db, $sql);
Unfortunately, using PDO this does not work with:
$stmt = $pdo->query($sql); or $stmt->execute();
I would be more than happy if someone could help me make this function work again!
I have excel table with several thousands of rows. Amount of columns changes through time. I use this code to create columns in MySQL:
$headings = $sheet->rangeToArray('A1:' . $highestColumn . 1,
NULL,
TRUE,
FALSE);
$i=1;
$c=1;
$name = 'name';
foreach($headings[0] as $x => $x_value) {
$date = date('d-m-y', PHPExcel_Shared_Date::ExcelToPHP($objWorksheet->getCellByColumnAndRow($c, $i)->getValue()));
$sql = "ALTER TABLE stats ADD `$date` INT(3) AFTER `$name`";
mysqli_query($connection, $sql);
var_dump($sql);
$c++;
$name = $date;
}
After I have to insert data into each column I have created before. This is how I get data from xlsx:
while ($row <= $highestRow):
$rowData = $sheet->rangeToArray('A' . $row . ':' . $highestColumn . $row,
NULL,
TRUE,
FALSE);
foreach($rowData[0] as $x => $x_value) {
echo $x_value, '<br>';
}
endwhile;
I don't get how to form MySql query to import all rows in database.
Thank you in advance.
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
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());
}
?>
I am building a dynamic table using php, pear HTML_Table, and sql.
My the first query pulls the information for the table headers, and then pear uses this to create the headers. The next query pulls the information from multiple tables to return the correct data sets. Next, I need to tie these data sets to the headers and display the results down each matching column. I am able to display all of the data, but not properly. Column 0 starts at row 1, and displays the current 4 test items, column 1 starts at row 5 and displays the current 2 test items, column 2 then starts at 7...How can I get the column count to reset to 0 after the previous column runs out of matching data? The other part of this problem is that I also need to apply rowSpans to the inserted data as this is a scheduling project. I have been at this for a week now and have been unable to find any relevant examples or suggestions. What am I missing, as I don't think this should be such a difficult task?
Code below.
<?php
session_start();
include_once("../php/functions.php");
include_once("HTML/TABLE.PHP");
$assetHead = headers('Assets', $_SESSION['deptID']);
$captionHeading = $_SESSION['dept'];
$conn = connect();
$attrs = array( 'id' => 'main',
'width' => '100%',
'Border' => '1');
$table = new HTML_Table($attrs);
$table->setAutoGrow(true);
$table->setAutoFill('n/a');
$sql_assets = "select AssetName, AssetID
from Assets
where Assets.DepartmentID = $_SESSION[deptID]";
$stmt1 = sqlsrv_query($conn, $sql_assets);
if ($stmt1)
{
$rows = sqlsrv_has_rows($stmt1);
if ($rows === true)
{
while( $row = sqlsrv_fetch_array( $stmt1, SQLSRV_FETCH_ASSOC) )
{
$assetName [] = $row['AssetName'];
$assetID [] = $row['AssetID'];
}
}
}
else
{
die( print_r(sqlsrv_errors(), true));
}
$i = 0;
foreach($assetName as $val)
{
$table->setHeaderContents(0, $i++, $val);
unset($val);
}
sqlsrv_close($conn);
$conn = connect();
$tsql = "select + 'Job#' + CAST (JobNum AS VARCHAR(10))+ ' ' + Description AS newField, datediff(MI,StartTime, EndTime) / 15 as 'RowSpan', AssetName, AssetID
from Calendar_View, Departments, Status, Assets
where Departments.DepartmentName = '$captionHeading' and Calendar_View.Department = Departments.DepartmentID and AssetStatus = Status.StatusID and
Calendar_View.Asset = Assets.AssetID
order by AssetID asc";
$rowcounter = 1;
$stmt = sqlsrv_query($conn, $tsql);
if ($stmt)
{
while( $row = sqlsrv_fetch_array( $stmt, SQLSRV_FETCH_ASSOC) )
{
for ($i = 0; $i < count($assetID);$i++)
if ($row['AssetID'] == $assetID[$i])
$table->setCellContents($rowcounter++,$i,$row['newField']);
}
}
else
{
die( print_r(sqlsrv_errors(), true));
}
sqlsrv_close($conn);
echo $table->toHTML();
?>
</body>
</html>
$headerCounter = 0;
$stmt = sqlsrv_query($conn, $tsql);
if ($stmt)
{
$rows = sqlsrv_has_rows($stmt);
if ($rows === true)
{
$cellCounter = 1;
$cellPosition = 0;
$rowCounter = 1;
echo "Header position outside of loop: $headerCounter ";
while( $row = sqlsrv_fetch_array( $stmt, SQLSRV_FETCH_ASSOC) )
{
if ($row['AssetID'] == $assetID[$headerCounter])
{
echo "<br>begining of if statement<br>";
echo "Header (beginning of loop) = " . $assetName[$headerCounter] . "<br>" ;
echo "Header Position (beginning of loop) = " . $headerCounter . "<br>";
echo "Row position = " . $rowCounter . "<br>" ;
echo "Cell position = " . $cellPosition . "<br>";
echo "<pre>";
var_dump($row);
echo "</pre>";
/*foreach ($row as $result)
{
echo "<pre>";
var_dump($result);
echo "</pre>";
}*/
$table->setCellContents($rowCounter,$cellPosition,$row['newField']);
//echo "$headerCounter";
//echo "<br>";
echo "Header Name (end of loop) = " . $assetName[$headerCounter] . "<br>" ;
echo "Header Position (end of loop) = " . $headerCounter . "<br>";
echo "Row position = " . $rowCounter . "<br>" ;
echo "Cell position = " . $cellPosition . "<br>";
//$cellPosition++;
$rowCounter++;
echo "end of if statment<br><br>";
}
else
{
echo "<br>header before increase $headerCounter";
echo "<br>header name outside of loop, before increment $assetName[$headerCounter]";
$cellPosition++;
$rowCounter = 1;
$headerCounter++;
$table->setCellContents($rowCounter,$cellPosition,$row['newField']);
echo "<br>header name outside of loop, after increment $assetName[$headerCounter]";
echo "<br>header increased by 1, now: $headerCounter";
}
}//$headerCounter++;
//$table->setCellContents($rowCounter,$cellPosition,$row['newField']);
}
Ok, the problem was that I was not incrementing the rowcounter variable after i left the initial loop. The following line:
$cellPosition++;
$rowCounter = 1;
$headerCounter++;
$table->setCellContents($rowCounter,$cellPosition,$row['newField']);
Should have been:
$cellPosition++;
$rowCounter = 1;
$headerCounter++;
$table->setCellContents($rowCounter++,$cellPosition,$row['newField']);
Sorry for the poor formatting of the original post. I am not sure what went wrong.