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
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´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());
}
?>
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;
}
}
?>
I am trying to display data in table form with 3 columns. Each should have a main category with some drop down lists. I get all the information to display but all is in one column and the drop down information does not display with the correct heading.
echo "<table>";
while ($row = mysql_fetch_array($result)) {
$count = 1;
if ($count = 1) {
$sCatID = ($row['CatID']);
echo "<tr valign='top'><td><b><a href='#" . $sCatID . "'>" . $sCatID . "</a></b><br>";
// column 1 categories
$result2 = mysql_query("SELECT * FROM test_prefixSubCat WHERE CatID=$sCatID");
// sub-cats
while ($row2 = mysql_fetch_array($result2)) {
$sSub = ($row2['CatID']);
$sSubID = ($row2['SubID']);
echo "<dd><a href='#'>" . $sSub . "</a><br>";
echo "</td>";
}
$count = 2;
} elseif ($count = 2) {
$sCatID = ($row['CatID']);
echo "<td><b><a href='.$sCatID.'>" . $sCatID . "</a></b><br>";
// column 1 categories
$result2 = mysql_query("SELECT * FROM test_prefixSubCat WHERE CatID=$sCatID");
// sub-cats
while ($row2 = mysql_fetch_array($result2)) {
$sSub = ($row2['CatID']);
$sSubID = ($row2['SubID']);
echo "<dd><a href='#'>" . $row2['Sub'] . "</a><br>";
echo "</td>";
}
$count = 3;
} elseif ($count = 3) {
$sCatID = ($row['CatID']);
echo "<td><b><a href='.$sCatID.'>" . $sCatID . "</a></b><br>";
// column 1 categories
$result2 = mysql_query("SELECT * FROM test_prefixSubCat WHERE CatID=$sCatID");
// sub-cats
while ($row2 = mysql_fetch_array($result2)) {
$sSub = ($row2['CatID']);
$sSubID = ($row2['SubID']);
echo "<dd><a href='.$sSub.'>" . $sSub . "</a><br>";
echo "</td></tr>";
}
$count = 1;
}
}
if ($count = 2) {
echo "<td> </td><td> </td></tr>";
} elseif ($count = 3) {
echo "<td> </td></tr>";
}
echo "</table>";
It doesn't seem to close the rows and table correctly... And it is also putting some of the drop down items before it displays the first heading.
If i display it in only one column it is working fine.
You should use == instead of single = in your if statements. Else it would execute everytime as that condition is always true.
At the moment I'm using a WHERE loop to display 2 columns of information in my database. Here's the code:
$sql2 = sprintf($rawsql2, mysql_real_escape_string($id));
$result2 = mysql_query($sql2);
/*These if & while statements decide whether or not the information should be displayed. If no results are returned from the query above then an alternative message is shown.*/
if (mysql_num_rows($result2) > 0) {
while ($row = mysql_fetch_array($result2, MYSQL_ASSOC)) {
echo $row["open"] . "-" . $row["close"] . "<br/><br/>";
}
}
else {
echo "Error";
}
This outputs the following:
08:00:00-12:30:00
13:30:00-16:30:00
09:00:00-17:00:00
18:00:00-20:00:00
09:00:00-17:00:00
18:00:00-20:00:00
08:00:00-17:00:00
18:00:00-20:00:00
09:00:00-17:00:00
18:00:00-20:00:00
Now, what I need to do is group every 2 lines that are turned so instead it would look like:
08:00:00-12:30:00 13:30:00-16:30:00
09:00:00-17:00:00 18:00:00-20:00:00
09:00:00-17:00:00 18:00:00-20:00:00
08:00:00-17:00:00 18:00:00-20:00:00
09:00:00-17:00:00 18:00:00-20:00:00
Is this possible? Thanks for any help
edit: Thanks for all the answers everyone...I used Shakti's answer as it was the first one I saw but by the looks of it everyone's are pretty similar.
if(mysql_num_rows($result2) > 0)
{
$count=0;
while ($row = mysql_fetch_array($result2, MYSQL_ASSOC))
{
echo $row["open"] . "-" . $row["close"] ;
if ($count % 2 !=0 )
{
echo "<br/><br/>";
}
$count++;
}
}
try this:
$lines = 1;
if(mysql_num_rows($result2) > 0) {
while ($row = mysql_fetch_array($result2, MYSQL_ASSOC)) {
echo $row["open"] . "-" . $row["close"];
echo (($lines%2 == 0)?"<br/><br/>":'');
$lines++;
}
} else {
echo "Error";
}
if(mysql_num_rows($result2) > 0){
$counter = 0;
while($row = mysql_fetch_array($result2, MYSQL_ASSOC)){
echo $row["open"] . "-" . $row["close"] . " ";
if(++$counter % 2 == 0){
echo "<br/><br/>";
$counter = 0;
}
}
}
if($result2) {
$printTimes = function($r) {echo $row["open"] . "-" . $row["close"];};
$newLine = false;
while ($row = mysql_fetch_assoc($result2))
{
$printTimes($row);
echo $newLine ? '<br /><br />' : ' ';
$newLine = !$newLine;
}
}
My version of code.
$sql2 = sprintf($rawsql2, mysql_real_escape_string($id));
$result2 = mysql_query($sql2);
if(mysql_num_rows($result2) > 0) {
while (true) {
$row1 = mysql_fetch_array($result2, MYSQL_ASSOC);
$row2 = mysql_fetch_array($result2, MYSQL_ASSOC);
if (!($row1 and $row2)) break;
echo $row1["open"] . "-" . $row1["close"] . " ";
echo $row2["open"] . "-" . $row2["close"] . "<br/><br/>";
}
} else {
echo "Error";
}
$i=1;
while ($row = mysql_fetch_array($result2, MYSQL_ASSOC)) {
if ($i == 1) {
echo $row["open"] . "-" . $row["close"];
$i++;
} else {
echo $row["open"] . "-" . $row["close"] . "<br /><br />";
$i=1;
}
Output <br/><br/> only on every other iteration of the loop. (BTW, a <p> or <ul> or <div> would be more semantic.)
$counter = 0;
while ($row = mysql_fetch_array($result2, MYSQL_ASSOC)) {
echo $row["open"] . "-" . $row["close"] . " ";
// Break line after every two items
$counter = ($counter + 1) % 2;
if ($counter == 0)
echo "<br/><br/>";
}
$sql2 = sprintf($rawsql2, mysql_real_escape_string($id));
$result2 = mysql_query($sql2);
/*These if & while statements decide whether or not the information should be displayed. If no results are returned from the query above then an alternative message is shown.*/
int row_count=mysql_num_rows($result2)
if(row_count > 0) {
while ($row = mysql_fetch_array($result2, MYSQL_ASSOC)) {
row_count--;
echo $row["open"] . "-" . $row["close"] ;
if(row_count > 0 && ($row = mysql_fetch_array($result2, MYSQL_ASSOC)){
row_count--;
echo $row["open"] . "-" . $row["close"] ;
}
"<br/><br/>"
}
} else {
echo "Error";
}
should do it, u may need to catch if there is an odd number