Remove empty First rows in PHPexcel - php

I'm Uploading the excel file to the database on the website using phpexcel.
But first row is being skiped and entered my data.
The results is shown in the picture below.
i need a help..
How can I solve?
I have the following code.
<?
include_once('./_common.php'); //database option
include 'Classes/PHPExcel.php';
include 'Classes/PHPExcel/IOFactory.php'; //load phpexcel
$up_file = "aaa.xlsx";
try {
$objReader = PHPExcel_IOFactory::createReaderForFile($up_file);
//set the read only
$objReader->setReadDataOnly(true);
//read a excel file
$objExcel = $objReader->load($up_file);
// select first cell
$objExcel->setActiveSheetIndex(0);
$objWorksheet = $objExcel->getActiveSheet();
$rowIterator = $objWorksheet->getRowIterator();
foreach ($rowIterator as $row) {
$cellIterator = $row->getCellIterator();
$cellIterator->setIterateOnlyExistingCells(false);
}
$maxRow = $objWorksheet->getHighestRow();
$maxCell = $objWorksheet->getHighestColumn();
for ($i = 0 ; $i <= $maxRow; $i++) {
$acell = $objWorksheet->getCell('A' . $i)->getValue(); // A
$bcell = $objWorksheet->getCell('B' . $i)->getValue(); // B
$acell = addslashes($acell);
$bcell = addslashes($bcell);
//$sql = "insert into echo_test (a,b,c,d,e) values ('$a','$b','$c','$d','$e')";
$sql = "insert into echo_excel set
bcat = '$acell',
scat = '$bcell',
";
sql_query($sql);
}
echo $maxRow . " Data inserting finished !";
} catch (exception $e) {
echo 'error!';
}
?>

Simply test the $bcat variable to see if it is empty before trying to insert data into your table.
$acell = $objWorksheet->getCell('A' . $i)->getValue(); // A
$bcell = $objWorksheet->getCell('B' . $i)->getValue(); // B
if (empty($bcell)) {continue;} // no value for bcat so go to the next row
$acell = addslashes($acell);
$bcell = addslashes($bcell);

Related

Excel Upload giving me blank sheet

I am uploading data from my database into excel using PHPExcel. The download occurs correctly only that it is returning an empty excel sheet for me and i dont seem to get what the problem really is. I would be glad if you could help me out. Find below my code snippet for the upload.
<?php
include("connection/db.php");
$uploadedStatus = 0;
$msg="";
include 'Classes/PHPExcel/IOFactory.php';
if(isset($_POST['submit'])){
$schId=$_POST['schId'];
$program=$_POST['program'];
$objPHPExcel = new PHPExcel();
if($program=="All"){
echo $query1 = "SELECT * FROM studentrec WHERE schId='$schId'";
}
else{
$query1 = "SELECT * FROM studentrec WHERE schId='$schId' AND program='$program'";
}
$exec1 = mysqli_query($conn,$query1) or die ("Error in Query1".mysqli_error());
$serialnumber=0;
//Set header with temp array
$tmparray =array("Student ID","First Name","Last Name");
//take new main array and set header array in it.
$sheet =array($tmparray);
while ($res1 = mysqli_fetch_array($exec1))
{
$tmparray =array();
$serialnumber = $serialnumber + 1;
array_push($tmparray,$serialnumber);
$employeelogin = $res1['stdId'];
array_push($tmparray,$employeelogin);
$employeename = $res1['fst_name'];
array_push($tmparray,$employeename);
$lst_name = $res1['lst_name'];
array_push($tmparray,$lst_name);
array_push($sheet,$tmparray);
}
header('Content-type: application/vnd.ms-excel');
header('Content-Disposition: attachment; filename="name.xlsx"');
$worksheet = $objPHPExcel->getActiveSheet();
foreach($sheet as $row => $columns) {
foreach($columns as $column => $data) {
$worksheet->setCellValueByColumnAndRow($column, $row + 1, $data);
}
}
//make first row bold
$objPHPExcel->getActiveSheet()->getStyle("A1:I1")->getFont()->setBold(true);
$objPHPExcel->setActiveSheetIndex(0);
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
$objWriter->save(str_replace('.php', '.xlsx', __FILE__));
}
?>

How to put line breaks every 30 records

I have a program that writes MySQL data to Excel via PHPExcel and I am having no errors but the problem is they don't have any line breaks in every 30 records.
How can I achieve this programmatically in PHPExcel?
This is my code:
require 'PHPExcel.php';
require 'PHPExcel/Writer/Excel2007.php';
require 'PHPExcel/IOFactory.php';
$user = "root";
$pass = "admin";
$host = "localhost";
$db = "hrtms";
$dept = "WAREHOUSE/DRIVER";
$TimeIn = "";
$LunchOut = "";
$LunchIn = "";
$TimeOut = "";
$objPHPExcel = new PHPExcel();
try{
$con = new PDO("mysql:host=$host;dbname=$db",$user,$pass);
$con->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);
$con->exec('SET NAMES "utf8"');
}
catch(PDOException $e){
echo $e->getMessage();
exit();
}
try{
$query = $con->prepare("SELECT * FROM emptb WHERE Department = :dept ORDER BY id ASC");
$query->bindParam(':dept',$dept);
$query->execute();
}
catch(PDOException $e){
echo $e->getMessage();
exit();
}
$objPHPExcel->setActiveSheetIndex(0);
//set default font
$objPHPExcel->getActiveSheet()->getStyle('B1')->getFont()->setName('Verdana');
//set titles
$objPHPExcel->getActiveSheet()->SetCellValue('B1','EMPLOYEE ATTENDANCE LOGS');
//$objPHPExcel->getActiveSheet()->getStyle('B1')->getAlignment()->setWrapText(true);
//merge cells
$objPHPExcel->getActiveSheet()->mergeCells('B1:T1');
$objPHPExcel->getActiveSheet()->mergeCells('C4:D4');
$objPHPExcel->getActiveSheet()->mergeCells('E8:F8');
//set text alignment
$objPHPExcel->getActiveSheet()->getStyle('B1')->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
$objPHPExcel->getActiveSheet()->getStyle('B1')->getFont()->setBold(true);
$objPHPExcel->getActiveSheet()->getStyle('B1')->getFont()->setSize(18);
$objPHPExcel->getActiveSheet()->getStyle('B1')->getFill()->getStartColor()->setARGB('#333');
//set column width
$objPHPExcel->getActiveSheet()->getColumnDimension('A')->setWidth(6.14);
$objPHPExcel->getActiveSheet()->getColumnDimension('B')->setWidth(0.67);
$objPHPExcel->getActiveSheet()->getColumnDimension('C')->setWidth(10.86);
$objPHPExcel->getActiveSheet()->getColumnDimension('D')->setWidth(1.43);
$objPHPExcel->getActiveSheet()->getColumnDimension('E')->setWidth(9.71);
$objPHPExcel->getActiveSheet()->getColumnDimension('F')->setWidth(1.43);
$objPHPExcel->getActiveSheet()->getColumnDimension('G')->setWidth(6.71);
$objPHPExcel->getActiveSheet()->getColumnDimension('H')->setWidth(1.57);
$objPHPExcel->getActiveSheet()->getColumnDimension('I')->setWidth(2);
$objPHPExcel->getActiveSheet()->getColumnDimension('J')->setWidth(9);
$objPHPExcel->getActiveSheet()->getColumnDimension('K')->setWidth(0.58);
$objPHPExcel->getActiveSheet()->getColumnDimension('L')->setWidth(0.92);
$objPHPExcel->getActiveSheet()->getColumnDimension('M')->setWidth(9);
$objPHPExcel->getActiveSheet()->getColumnDimension('N')->setWidth(1.71);
$objPHPExcel->getActiveSheet()->getColumnDimension('O')->setWidth(2.43);
$objPHPExcel->getActiveSheet()->getColumnDimension('P')->setWidth(6.14);
$objPHPExcel->getActiveSheet()->getColumnDimension('Q')->setWidth(1.71);
$objPHPExcel->getActiveSheet()->getColumnDimension('R')->setWidth(9.29);
$objPHPExcel->getActiveSheet()->getColumnDimension('S')->setWidth(4);
$objPHPExcel->getActiveSheet()->getColumnDimension('T')->setWidth(0.67);
$objPHPExcel->getActiveSheet()->getColumnDimension('U')->setWidth(0.67);
//set text alignment
$rowCount = 4;
while($row = $query->fetch())
{
$rowTitle = $rowCount + 2;
$rowTitle1 = $rowCount + 4;
//data label
$objPHPExcel->getActiveSheet()->getStyle('C'.$rowCount)->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
$objPHPExcel->getActiveSheet()->mergeCells('C'.($rowCount).':D'.($rowCount));
$objPHPExcel->getActiveSheet()->getStyle('C'.$rowCount)->getAlignment()->setWrapText(true);
$objPHPExcel->getActiveSheet()->getStyle('C'.$rowCount)->getFont()->setBold(true);
$objPHPExcel->getActiveSheet()->getStyle('C'.$rowCount)->getFont()->setSize(12);
$objPHPExcel->getActiveSheet()->getStyle('C'.$rowCount)->getFont()->setName('Arial');
$objPHPExcel->getActiveSheet()->SetCellValue('C'.$rowCount,'ID No:');
$objPHPExcel->getActiveSheet()->getStyle('C'.$rowTitle)->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
$objPHPExcel->getActiveSheet()->mergeCells('C'.($rowTitle).':D'.($rowTitle));
$objPHPExcel->getActiveSheet()->getStyle('C'.$rowTitle)->getAlignment()->setWrapText(true);
$objPHPExcel->getActiveSheet()->getStyle('C'.$rowTitle)->getFont()->setBold(true);
$objPHPExcel->getActiveSheet()->getStyle('C'.$rowTitle)->getFont()->setSize(12);
$objPHPExcel->getActiveSheet()->getStyle('C'.$rowTitle)->getFont()->setName('Arial');
$objPHPExcel->getActiveSheet()->SetCellValue('C'.$rowTitle,'Name:');
$objPHPExcel->getActiveSheet()->getStyle('I'.$rowCount)->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
$objPHPExcel->getActiveSheet()->mergeCells('I'.($rowCount).':J'.($rowCount));
$objPHPExcel->getActiveSheet()->getStyle('I'.$rowCount)->getAlignment()->setWrapText(true);
$objPHPExcel->getActiveSheet()->getStyle('I'.$rowCount)->getFont()->setBold(true);
$objPHPExcel->getActiveSheet()->getStyle('I'.$rowCount)->getFont()->setSize(12);
$objPHPExcel->getActiveSheet()->getStyle('I'.$rowCount)->getFont()->setName('Arial');
$objPHPExcel->getActiveSheet()->SetCellValue('I'.$rowCount,'Dept:');
$objPHPExcel->getActiveSheet()->getStyle('C'.$rowTitle1)->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
$objPHPExcel->getActiveSheet()->mergeCells('C'.($rowTitle1).':D'.($rowTitle1));
$objPHPExcel->getActiveSheet()->getStyle('C'.$rowTitle1)->getAlignment()->setWrapText(true);
$objPHPExcel->getActiveSheet()->getStyle('C'.$rowTitle1)->getFont()->setBold(true);
$objPHPExcel->getActiveSheet()->getStyle('C'.$rowTitle1)->getFont()->setSize(12);
$objPHPExcel->getActiveSheet()->getStyle('C'.$rowTitle1)->getFont()->setName('Arial');
$objPHPExcel->getActiveSheet()->SetCellValue('C'.$rowTitle1,'Section:');
$objPHPExcel->getActiveSheet()->getStyle('I'.$rowTitle1)->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
$objPHPExcel->getActiveSheet()->mergeCells('I'.($rowTitle1).':J'.($rowTitle1));
$objPHPExcel->getActiveSheet()->getStyle('I'.$rowTitle1)->getAlignment()->setWrapText(true);
$objPHPExcel->getActiveSheet()->getStyle('I'.$rowTitle1)->getFont()->setBold(true);
$objPHPExcel->getActiveSheet()->getStyle('I'.$rowTitle1)->getFont()->setSize(12);
$objPHPExcel->getActiveSheet()->getStyle('I'.$rowTitle1)->getFont()->setName('Arial');
$objPHPExcel->getActiveSheet()->SetCellValue('I'.$rowTitle1,'Line:');
//data contents
$objPHPExcel->getActiveSheet()->mergeCells('E'.($rowCount).':G'.($rowCount));
$objPHPExcel->getActiveSheet()->getStyle('E'.$rowCount)->getAlignment()->setWrapText(true);
$objPHPExcel->getActiveSheet()->SetCellValue('E'.$rowCount,$row['EmpID']);
$objPHPExcel->getActiveSheet()->getStyle('E'.$rowCount)->getFont()->setBold(true);
$objPHPExcel->getActiveSheet()->getStyle('E'.$rowCount)->getFont()->setSize(12);
$objPHPExcel->getActiveSheet()->getStyle('E'.$rowCount)->getFont()->setName('Arial');
$objPHPExcel->getActiveSheet()->mergeCells('E'.($rowTitle).':S'.($rowTitle));
$objPHPExcel->getActiveSheet()->SetCellValue('E'.$rowTitle,$row['Lastname'] . ', ' . $row['Firstname']);
$objPHPExcel->getActiveSheet()->getStyle('E'.$rowTitle)->getFont()->setBold(true);
$objPHPExcel->getActiveSheet()->getStyle('E'.$rowTitle)->getFont()->setSize(12);
$objPHPExcel->getActiveSheet()->getStyle('E'.$rowTitle)->getFont()->setName('Arial');
$objPHPExcel->getActiveSheet()->mergeCells('L'.($rowCount).':S'.($rowCount));
$objPHPExcel->getActiveSheet()->SetCellValue('L'.$rowCount,$row['Department']);
$objPHPExcel->getActiveSheet()->getStyle('L'.$rowCount)->getFont()->setBold(true);
$objPHPExcel->getActiveSheet()->getStyle('L'.$rowCount)->getFont()->setSize(12);
$objPHPExcel->getActiveSheet()->getStyle('L'.$rowCount)->getFont()->setName('Arial');
$objPHPExcel->getActiveSheet()->SetCellValue('E'.$rowTitle1,$row['SectionName']);
$objPHPExcel->getActiveSheet()->getStyle('E'.$rowTitle1)->getFont()->setBold(true);
$objPHPExcel->getActiveSheet()->getStyle('E'.$rowTitle1)->getFont()->setSize(12);
$objPHPExcel->getActiveSheet()->getStyle('E'.$rowTitle1)->getFont()->setName('Arial');
$objPHPExcel->getActiveSheet()->SetCellValue('L'.$rowTitle1,$row['LineName']);
$objPHPExcel->getActiveSheet()->getStyle('L'.$rowTitle1)->getFont()->setBold(true);
$objPHPExcel->getActiveSheet()->getStyle('L'.$rowTitle1)->getFont()->setSize(12);
$objPHPExcel->getActiveSheet()->getStyle('L'.$rowTitle1)->getFont()->setName('Arial');
$rowCount++;
try{
$subquery = $con->prepare("SELECT c.dt,a.TimeIn,a.LunchOut,a.LunchIn,a.RNDOUT FROM cal c LEFT JOIN attendance a ON a.ValidDate = c.dt
AND a.EmpID = :id WHERE c.dt BETWEEN DATE('2015-08-01') AND DATE('2015-08-30') GROUP BY c.dt ORDER BY c.dt ASC");
$subquery->bindParam(':id',$row['EmpID']);
$subquery->execute();
}
catch(PDOException $e){
echo $e->getMessage();
exit();
}
$rowCount += 6;
while($subrow = $subquery->fetch())
{
if($subrow['TimeIn'] == "00:00:00")
{
$TimeIn = "";
}
else
{
$TimeIn = $subrow['TimeIn'];
}
if($subrow['LunchOut']=="00:00:00")
{
$LunchOut = "";
}
else
{
$LunchOut = $subrow['LunchOut'];
}
if($subrow['LunchIn']=="00:00:00")
{
$LunchIn = "";
}
else
{
$LunchIn = $subrow['LunchIn'];
}
if($subrow['RNDOUT']=="00:00:00")
{
$TimeOut = "";
}
else
{
$TimeOut = $subrow['RNDOUT'];
}
$titleRow = 10;
$objPHPExcel->getActiveSheet()->getStyle('C'.$titleRow)->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
$objPHPExcel->getActiveSheet()->getStyle('C'.$titleRow)->getFont()->setBold(true);
$objPHPExcel->getActiveSheet()->getStyle('C'.$titleRow)->getFont()->setSize(11);
$objPHPExcel->getActiveSheet()->getStyle('C'.$titleRow)->getFont()->setName('Arial');
$objPHPExcel->getActiveSheet()->SetCellValue('C'.$titleRow,'Date');
$objPHPExcel->getActiveSheet()->getStyle('E'.$titleRow)->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
$objPHPExcel->getActiveSheet()->getStyle('E'.$titleRow)->getFont()->setBold(true);
$objPHPExcel->getActiveSheet()->getStyle('E'.$titleRow)->getFont()->setSize(11);
$objPHPExcel->getActiveSheet()->getStyle('E'.$titleRow)->getFont()->setName('Arial');
$objPHPExcel->getActiveSheet()->SetCellValue('E'.$titleRow,'TimeIn');
$objPHPExcel->getActiveSheet()->getStyle('G'.$titleRow)->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
$objPHPExcel->getActiveSheet()->getStyle('G'.$titleRow)->getFont()->setBold(true);
$objPHPExcel->getActiveSheet()->getStyle('G'.$titleRow)->getFont()->setSize(11);
$objPHPExcel->getActiveSheet()->getStyle('G'.$titleRow)->getFont()->setName('Arial');
$objPHPExcel->getActiveSheet()->SetCellValue('G'.$titleRow,'LunchOut');
$objPHPExcel->getActiveSheet()->getStyle('J'.$titleRow)->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
$objPHPExcel->getActiveSheet()->getStyle('J'.$titleRow)->getFont()->setBold(true);
$objPHPExcel->getActiveSheet()->getStyle('J'.$titleRow)->getFont()->setSize(11);
$objPHPExcel->getActiveSheet()->getStyle('J'.$titleRow)->getFont()->setName('Arial');
$objPHPExcel->getActiveSheet()->SetCellValue('J'.$titleRow,'LunchIn');
$objPHPExcel->getActiveSheet()->getStyle('M'.$titleRow)->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
$objPHPExcel->getActiveSheet()->getStyle('M'.$titleRow)->getFont()->setBold(true);
$objPHPExcel->getActiveSheet()->getStyle('M'.$titleRow)->getFont()->setSize(11);
$objPHPExcel->getActiveSheet()->getStyle('M'.$titleRow)->getFont()->setName('Arial');
$objPHPExcel->getActiveSheet()->SetCellValue('M'.$titleRow,'TimeOut');
$titleRow++;
$objPHPExcel->getActiveSheet()->getStyle('C'.$rowCount)->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
$objPHPExcel->getActiveSheet()->getStyle('C'.$rowCount)->getFont()->setSize(10);
$objPHPExcel->getActiveSheet()->getStyle('C'.$rowCount)->getFont()->setName('Arial');
$objPHPExcel->getActiveSheet()->SetCellValue('C'.$rowCount,$subrow['dt']);
$objPHPExcel->getActiveSheet()->getStyle('E'.$rowCount)->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
$objPHPExcel->getActiveSheet()->getStyle('E'.$rowCount)->getFont()->setSize(10);
$objPHPExcel->getActiveSheet()->getStyle('E'.$rowCount)->getFont()->setName('Arial');
$objPHPExcel->getActiveSheet()->SetCellValue('E'.$rowCount,$TimeIn);
$objPHPExcel->getActiveSheet()->getStyle('G'.$rowCount)->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
$objPHPExcel->getActiveSheet()->getStyle('G'.$rowCount)->getFont()->setSize(10);
$objPHPExcel->getActiveSheet()->getStyle('G'.$rowCount)->getFont()->setName('Arial');
$objPHPExcel->getActiveSheet()->SetCellValue('G'.$rowCount,$LunchOut);
$objPHPExcel->getActiveSheet()->getStyle('J'.$rowCount)->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
$objPHPExcel->getActiveSheet()->getStyle('J'.$rowCount)->getFont()->setSize(10);
$objPHPExcel->getActiveSheet()->getStyle('J'.$rowCount)->getFont()->setName('Arial');
$objPHPExcel->getActiveSheet()->SetCellValue('J'.$rowCount,$LunchIn);
$objPHPExcel->getActiveSheet()->getStyle('M'.$rowCount)->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
$objPHPExcel->getActiveSheet()->getStyle('M'.$rowCount)->getFont()->setSize(10);
$objPHPExcel->getActiveSheet()->getStyle('M'.$rowCount)->getFont()->setName('Arial');
$objPHPExcel->getActiveSheet()->SetCellValue('M'.$rowCount,$TimeOut);
$rowCount++;
}
}
$excelWriter = PHPExcel_IOFactory::createWriter($objPHPExcel,'Excel2007');
header('Content-Type:application/ms-excel');
header('Content-Disposition:attachment;filename="'.$dept.'.xlsx"');
header('Cache-Control:max-age=0');
$excelWriter->save('php://output');
If you mean every 30 rows of the spreadsheet, then use the print setup options as described in the documentation:
$objPHPExcel->getActiveSheet()
->setBreak('A10' , PHPExcel_Worksheet::BREAK_ROW);
will set a print break on row 10
So just set those breakpoints every 30 rows as you're building the worksheet
You only need to use \n if you want to control exactly where a line wraps.
Example:
$objPHPExcel->getActiveSheet()->setCellValue('H5', "Hello\nWorld");
You should always use double quotes when you add escape sequences in a PHP string.

Timestamp is null after loading csv file into mysql

there is time stamp in my actual csv file but while loading it into mysql every thing is being loaded except the time stamp which remained as null. i am using mysql in phpadmin(i.e xampp),
code used is:
<?php
// specify connection info
$connect = mysql_connect('localhost','root','');
if (!$connect)
{
die('Could not <span id="IL_AD1" class="IL_AD">
connect to</span> MySQL: ' . mysql_error());
}
$cid =mysql_select_db('test',$connect); //specify db name
define('CSV_PATH','C:\Users\vijay\Desktop');
$csv_file = CSV_PATH . "\probe.csv"; // Name of your CSV file
$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["app_name"] = $csv_array[0];
$insert_csv["user_id"] = $csv_array[1];
$insert_csv["timestamp"] = $csv_array[2];
$insert_csv["event"] = $csv_array[3];
$insert_csv["feature"] = $csv_array[4];
$insert_csv["action_name"] = $csv_array[5];
$insert_csv["qoe_rate"] = $csv_array[6];
$insert_csv["qoe_rate_description"] = $csv_array[7];
$query = "insert into csvdata2 (app_name,user_id,timestamp,event,feature,action_name,qoe_rate,qoe_rate_description) VALUES('$insert_csv[app_name]','$insert_csv[user_id]',$insert_csv[timestamp],'$insert_csv[event]','$insert_csv[feature]','$insert_csv[action_name]',$insert_csv[qoe_rate],'$insert_csv[qoe_rate_description]')";
$n=mysql_query($query);
echo $n;
$i++;
}
fclose($csvfile);
echo "file data successfully imported to database!!";
mysql_close($connect);
?>
How to include the timestamp code so that i would get the exact timestamp data loaded into table without disturbing the other entries...thanks in advance
You are missing quotes
Here
$insert_csv[timestamp]
$insert_csv[qoe_rate]
Try now
$query = "insert into csvdata2 (app_name,user_id,timestamp,event,feature,action_name,qoe_rate,qoe_rate_description) VALUES('$insert_csv[app_name]','$insert_csv[user_id]','$insert_csv[timestamp]','$insert_csv[event]','$insert_csv[feature]','$insert_csv[action_name]','$insert_csv[qoe_rate]','$insert_csv[qoe_rate_description]')";
and follow what #Plenka mentioned in comment

export mysql data from two tables to excel using php and phpexcel

I am trying to get data from to mysql table and output to a single excel file. The data needs to come side-by-side.
But the output excel file contains only special characters instead of mysql data. Please point me to the right direction.
Here is my code:
<?php
// connection with the database
$dbhost = "localhost";
$dbuser = "root";
$dbpass = "redhat";
$dbname = "was";
mysql_connect($dbhost,$dbuser,$dbpass);
mysql_select_db($dbname);
// require the PHPExcel file
require 'phpexcel/Classes/PHPExcel.php';
//$q2 = "SELECT COUNT(*) FROM information_schema.tables WHERE table_schema = ".$dbname."";
$sql = "SHOW TABLES"; $res = mysql_query($sql); $num_tables = mysql_num_rows($res);
$table = $num_tables;
$i = 1;
echo $i;
echo $table;
// write all table names with a variable value like table1 table2 table3
// simple query
while($i <= $table){
//$query = "SELECT servicedate,recdate,dostoreclag,casesrec,scandate,casesentered,casespending,casecountdiff,entrydate,rcvdtolag FROM hos1report ORDER by id DESC";
$query = "SELECT servicedate,recdate,dostoreclag,casesrec,scandate,casesentered,casespending,casecountdiff,entrydate,rcvdtolag FROM hos".$i."report";
$headings = array('Service Date','Rec. Date','DOS to Rec. Lag','Cases Rec.','scan Date','Cases Entered','Cases Pending','Cases Count Diff','Entry Date','Rec. to Entry Lag');
if ($result = mysql_query($query) or die(mysql_error())) {
// Create a new PHPExcel object
$objPHPExcel = new PHPExcel();
$objPHPExcel->getActiveSheet()->setTitle('Report');
$rowNumber = 8;
if ($i == 1) {
$col = 'A';
} elseif ($i == 2) {
$col = 'L';
}
// $col = 'A';
foreach($headings as $heading) {
$objPHPExcel->getActiveSheet()->setCellValue($col.$rowNumber,$heading);
$col++;
}
// Loop through the result set
$rowNumber = 9;
while ($row = mysql_fetch_row($result)) {
if ($i == 1) {
$col = 'A';
} elseif ($i == 2) {
$col = 'L';
}
// $col = 'A';
// $col = 'A';
foreach($row as $cell) {
$objPHPExcel->getActiveSheet()->setCellValue($col.$rowNumber,$cell);
$col++;
}
$rowNumber++;
}
// Freeze pane so that the heading line won't scroll
$objPHPExcel->getActiveSheet()->freezePane('A2');
// Save as an Excel BIFF (xls) file
$i++;
}
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
header('Content-Type: application/vnd.ms-excel');
header('Content-Disposition: attachment;filename="report.xls"');
header('Cache-Control: max-age=0');
}
$objWriter->save('php://output');
exit();
echo 'a problem has occurred... no data retrieved from the database';
?>
Try this code :
<?php
// connection with the database
$dbhost = "localhost";
$dbuser = "root";
$dbpass = "redhat";
$dbname = "was";
mysql_connect($dbhost,$dbuser,$dbpass);
mysql_select_db($dbname);
// require the PHPExcel file
require 'phpexcel/Classes/PHPExcel.php';
//$q2 = "SELECT COUNT(*) FROM information_schema.tables WHERE table_schema = ".$dbname."";
$sql = "SHOW TABLES"; $res = mysql_query($sql); $num_tables = mysql_num_rows($res);
$table = $num_tables;
$i = 1;
echo $i;
echo $table;
// write all table names with a variable value like table1 table2 table3
// simple query
while($i <= $table){
//$query = "SELECT servicedate,recdate,dostoreclag,casesrec,scandate,casesentered,casespending,casecountdiff,entrydate,rcvdtolag FROM hos1report ORDER by id DESC";
$query = "SELECT servicedate,recdate,dostoreclag,casesrec,scandate,casesentered,casespending,casecountdiff,entrydate,rcvdtolag FROM hos".$i."report";
$headings = array('Service Date','Rec. Date','DOS to Rec. Lag','Cases Rec.','scan Date','Cases Entered','Cases Pending','Cases Count Diff','Entry Date','Rec. to Entry Lag');
if ($result = mysql_query($query) or die(mysql_error())) {
// Create a new PHPExcel object
$objPHPExcel = new PHPExcel();
$objPHPExcel->getActiveSheet()->setTitle('Report');
$rowNumber = 8;
if ($i == 1) {
$col = 'A';
} elseif ($i == 2) {
$col = 'L';
}
// $col = 'A';
foreach($headings as $heading) {
$objPHPExcel->getActiveSheet()->setCellValue($col.$rowNumber,$heading);
$col++;
}
// Loop through the result set
$rowNumber = 9;
while ($row = mysql_fetch_row($result)) {
if ($i == 1) {
$col = 'A';
} elseif ($i == 2) {
$col = 'L';
}
// $col = 'A';
// $col = 'A';
foreach($row as $cell) {
$objPHPExcel->getActiveSheet()->setCellValue($col.$rowNumber,$cell);
$col++;
}
$rowNumber++;
}
// Freeze pane so that the heading line won't scroll
$objPHPExcel->getActiveSheet()->freezePane('A2');
// Save as an Excel BIFF (xls) file
$i++;
}
// $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
// header('Content-Type: application/vnd.ms-excel');
// header('Content-Disposition: attachment;filename="report.xls"');
// header('Cache-Control: max-age=0');
}
// Instantiate a Writer to create an OfficeOpenXML Excel .xlsx file
$objWriter = new PHPExcel_Writer_Excel2007($objPHPExcel);
// Write the Excel file to filename some_excel_file.xlsx in the current directory
$objWriter->save('some_excel_file.xlsx');
// $objWriter->save('php://output');
exit();
echo 'a problem has occurred... no data retrieved from the database';
?>
Hope it run well... :)

Upload CSV to MySQL table using PHP - Ignoring the header in the CSV

I am using the following to upload CSV to a table in MYSQL database.
Question: How do I bypass the 1st field? - as in ignore the header - which is currently being saved in my table?
Code:
<?php
/********************************/
/* Code at http://legend.ws/blog/tips-tricks/csv-php-mysql-import/
/* Edit the entries below to reflect the appropriate values
/********************************/
$databasehost = "localhost";
$databasename = "test";
$databasetable = "sample";
$databaseusername ="test";
$databasepassword = "";
$fieldseparator = ",";
$lineseparator = "\n";
$csvfile = "filename.csv";
/********************************/
/* Would you like to add an ampty field at the beginning of these records?
/* This is useful if you have a table with the first field being an auto_increment integer
/* and the csv file does not have such as empty field before the records.
/* Set 1 for yes and 0 for no. ATTENTION: don't set to 1 if you are not sure.
/* This can dump data in the wrong fields if this extra field does not exist in the table
/********************************/
$addauto = 0;
/********************************/
/* Would you like to save the mysql queries in a file? If yes set $save to 1.
/* Permission on the file should be set to 777. Either upload a sample file through ftp and
/* change the permissions, or execute at the prompt: touch output.sql && chmod 777 output.sql
/********************************/
$save = 1;
$outputfile = "output.sql";
/********************************/
if(!file_exists($csvfile)) {
echo "File not found. Make sure you specified the correct path.\n";
exit;
}
$file = fopen($csvfile,"r");
if(!$file) {
echo "Error opening data file.\n";
exit;
}
$size = filesize($csvfile);
if(!$size) {
echo "File is empty.\n";
exit;
}
$csvcontent = fread($file,$size);
fclose($file);
$con = #mysql_connect($databasehost,$databaseusername,$databasepassword) or die(mysql_error());
#mysql_select_db($databasename) or die(mysql_error());
$lines = 0;
$queries = "";
$linearray = array();
foreach(split($lineseparator,$csvcontent) as $line) {
$lines++;
$line = trim($line," \t");
$line = str_replace("\r","",$line);
/************************************
This line escapes the special character. remove it if entries are already escaped in the csv file
************************************/
$line = str_replace("'","\'",$line);
/*************************************/
$linearray = explode($fieldseparator,$line);
$linemysql = implode("','",$linearray);
if($addauto)
$query = "insert into $databasetable values('','$linemysql');";
else
$query = "insert into $databasetable values('$linemysql');";
$queries .= $query . "\n";
#mysql_query($query);
}
#mysql_close($con);
if($save) {
if(!is_writable($outputfile)) {
echo "File is not writable, check permissions.\n";
}
else {
$file2 = fopen($outputfile,"w");
if(!$file2) {
echo "Error writing to the output file.\n";
}
else {
fwrite($file2,$queries);
fclose($file2);
}
}
}
echo "Found a total of $lines records in this csv file.\n";
?>
I has been did the same purpose at last week. Please refer this code. It may be help you.
if (isset($_POST['submit'])) {
//Path of Uploading file
$target = "upload_files/results/";
$filename = $_FILES['upload_result']['name'];
if(file_exists($target.$filename)) {
unlink($target.$filename);
}
move_uploaded_file($_FILES['upload_result']['tmp_name'], $target.$filename);
//Store the Detail into the Master table...[class_master]
$new_master = mysql_query("INSERT INTO result_master(classname,sectionname,examname,filename) Values('$class','$section','$examname','$filename')");
$filename1 = explode(".",$filename);
$file = preg_replace("/[^a-zA-Z0-9]+/", "", $filename1[0]);
// get structure from csv and insert db
ini_set('auto_detect_line_endings',TRUE);
$handle = fopen($target.$filename,'r');
// first row, structure
if ( ($data = fgetcsv($handle) ) === FALSE ) {
echo "Cannot read from csv $file";die();
}
$fields = array();
$field_count = 0;
for($i=0;$i<count($data); $i++) {
$f = trim($data[$i]);
if ($f) {
// normalize the field name, strip to 20 chars if too long
$f = substr(preg_replace ('/[^0-9a-z]/', '_', $f), 0, 20);
$field_count++;
$fields[] = $f.' VARCHAR(50)';
}
}
$drop = mysql_query("Drop table IF EXISTS $file;");
$sql = "CREATE TABLE $file (" . implode(', ', $fields) . ')';
echo $sql . "<br /><br />";
$db = mysql_query($sql);
while ( ($data = fgetcsv($handle) ) !== FALSE ) {
$fields = array();
for($i=0;$i<$field_count; $i++) {
$fields[] = '\''.addslashes($data[$i]).'\'';
}
$sql = "Insert into $file values(" . implode(', ', $fields) . ')';
echo $sql;
$db = mysql_query($sql);
}
fclose($handle);
ini_set('auto_detect_line_endings',FALSE);
}
You either assume that there is ALWAYS a header, or that any header will be commented by some character, I will show you the first. You can just wrap the insertion lines in a conditional block to check for this.
if( $lines != 0 ) // or $linemysql[0][0] == '#' (assuming # is a "comment")
{
if($addauto)
$query = "insert into $databasetable values('','$linemysql');";
else
$query = "insert into $databasetable values('$linemysql');";
}
That being said, PLEASE! Do not ever use the code you posted in any internet facing application, you are putting user-provided data directly into the database, so it would be trivial to make a csv file containing SQL injection attack and change your mysql password, steal your data, kill your cat or delete everything. You should also check the number of fields and such, what happens if the csv contains lines without the correct number of fields ?
Read up on http://en.wikipedia.org/wiki/SQL_injection
and also http://php.net/PDO
Use this code in removing the header in the csv file and upload the data in the database:
$header= 1;
if (($handle = fopen("data.csv", "r")) !== FALSE) {
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
if($header== 1)
{
$header++;
continue;
}
//do your code here saving into the database
}
fclose($handle);
}

Categories