I'm using PHPExcel to import xls to mysql.
I recently switched connection to PDO.
But then an error accord.
Fields in my xls that is NULL are no longer accepted.
Why? How can i change my code to accept NULL value?
PHP:
if(isset($_POST["Import"])){
echo 'Fortsätt...<br />';
echo $path=$_FILES["file"]["tmp_name"];
//Load file into PHPExcel
$objPHPExcel = PHPExcel_IOFactory::load($path);
//Loop threw file to get data
foreach ($objPHPExcel->getWorksheetIterator() as $worksheet) {
$worksheetTitle = $worksheet->getTitle();
$highestRow = $worksheet->getHighestRow(); // e.g. 10
$highestColumn = 'J'; //$worksheet->getHighestColumn(''); // e.g 'F'
$highestColumnIndex = PHPExcel_Cell::columnIndexFromString($highestColumn);
$nrColumns = ord($highestColumn) - 64;
//Echo file info
echo "<br>The worksheet ".$worksheetTitle." has ";
echo $nrColumns . ' columns (A-' . $highestColumn . ') ';
echo ' and ' . $highestRow . ' row.';
echo '<br>Data: <table border="1"><tr>';
//Loop threw colum, rows and cells
for ($row = 2; $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 = 2; $row <= $highestRow; ++ $row) {
$val=array();
for ($col = 0; $col < $highestColumnIndex; ++ $col) {
$cell = $worksheet->getCellByColumnAndRow($col, $row);
$val[] = $cell->getCalculatedValue();
}
// Prepare Query
$query = "INSERT INTO table(
objekt_nr,
objekt_rev,
element_nr,
element_hojd,
element_typ,
element_langd,
element_oppningar,
element_vikt,
element_ritare,
element_status)
VALUES (
:objekt_nr,
:objekt_rev,
:element_nr,
:element_hojd,
:element_typ,
:element_langd,
:element_oppningar,
:element_vikt,
:element_ritare,
:element_status
)";
// Security measures
$query_params = array(
':objekt_nr' => $val[0],
':objekt_rev' => $val[1],
':element_nr' => $val[2],
':element_hojd' => $val[3],
':element_typ' => $val[4],
':element_langd' => $val[5],
':element_oppningar' => $val[6],
':element_vikt' => $val[7],
':element_ritare' => $val[8],
':element_status' => $val[9]
);
try {
$stmt = $db->prepare($query);
$result = $stmt->execute($query_params);
}
catch(PDOException $ex){ die("Failed to run query: " . $ex->getMessage()); }
To accept a NULL value you have to edit the database table, not the code. Your message error is generated by MySQL, not the PHP.
Related
I am using phpexcel to send student record via excel in bulk and i want to post to api in json format.my output is below but i want in the format like below from which the api can save the each data in database.
My Controller:
$import = new ImportExcel();
if ($import->load(Yii::$app->request->post())) {
//upload path global parameters
Yii::$app->params['uploadPath'] = Yii::$app->basePath . '/web/upload/excel/';
$file = UploadedFile::getInstance($import, 'import');
$path = Yii::$app->params['uploadPath'] . $file;
$file->saveAs($path);
// Include PHPExcel_IOFactory
try {
$inputFileType = PHPExcel_IOFactory::identify($path);
$objReader = PHPExcel_IOFactory::createReader($inputFileType);
$objPHPExcel = $objReader->load($path);
} catch (Exception $e) {
die('Error loading file "' . pathinfo($path, PATHINFO_BASENAME) . '": ' . $e->getMessage());
}
// Get worksheet dimensions
$sheet = $objPHPExcel->getSheet(0);
$highestRow = $sheet->getHighestRow();
$highestColumn = $sheet->getHighestColumn();
$highestColumnIndex = PHPExcel_Cell::columnIndexFromString($highestColumn);
$worksheet = $objPHPExcel->setActiveSheetIndexbyName('Sheet1');
$worksheetTitle = $worksheet->getTitle();
// Loop through each row of the worksheet in turn
for ($row = 1; $row <= $highestRow; $row++) {
// Read a row of data into an array
$rowData = $sheet->rangeToArray('A' . $row . ':' . $highestColumn . $row,
NULL,
TRUE,
FALSE);
var_dump(json_encode($rowData));
}
}
OutPut:
string(70) "[["name","address","class","section","guardian","contact us","email"]]" string(107) "[["sugam pradhan","rambazar,pokhara-10",10,"A","jayandra kumar rajbhandari",61431910,"suyog844#gmail.com"]]" string(105) "[["Bill gurung","rambazar,pokhara-10",10,"A","jayandra kumar rajbhandari",61431910,"suyog844#gmail.com"]]" string(107) "[["Bimal poudelq","rambazar,pokhara-10",10,"A","jayandra kumar rajbhandari",61431910,"suyog844#gmail.com"]]" string(101) "[["Dam sir","rambazar,pokhara-10",10,"A","jayandra kumar rajbhandari",61431910,"suyog844#gmail.com"]]"
I want to post in :
[{'school_id':3,'name':'name1','image':'image1','guardian_name':'guardian_name1','address':'address1','contact_no':'111','email':'email1#mail.com','blood_grp':'A','d_o_b':'2001-01-01','class_id':1,'section_id':2,'roll_no':'1','enrolled_date':'2010-01-01','is_active':0},
You need to map first row as keys as far as I understood.
$row = 1; $result = [];
$keys = $sheet->rangeToArray('A' . $row . ':' . $highestColumn . $row,
NULL,
TRUE,
FALSE);
// Loop through each row of the worksheet in turn
for ($row = 2; $row <= $highestRow; $row++) {
// Read a row of data into an array
$rowData = $sheet->rangeToArray('A' . $row . ':' . $highestColumn . $row,
NULL,
TRUE,
FALSE);
$result[] = array_combine($keys,$rowData);
}
var_dump($result);
This way you will get what you need if 1st row is keys for your array.
I’m trying to write a if code, but can't figure out how.
In my database table i have the primary key id.
In the table i have objekt_nr & element_nr.
Now, before i call an INSTERT i need to check if objekt_nr with element_nr already exist.
If objekt_nr With element_nr exist. Then UPDATE instead of INSTERT. Only id can be unique.
example of table:
id......objekt_nr......element_nr
1.......1...............1
2.......1...............2
3.......1...............3
4.......2...............1
5.......2...............2
PHP:
if(isset($_POST["Import"])){
echo 'Fortsätt...<br />';
echo $path=$_FILES["file"]["tmp_name"];
//Load file into PHPExcel
$objPHPExcel = PHPExcel_IOFactory::load($path);
//Loop threw file to get data
foreach ($objPHPExcel->getWorksheetIterator() as $worksheet) {
$worksheetTitle = $worksheet->getTitle();
$highestRow = $worksheet->getHighestRow(); // e.g. 10
$highestColumn = 'J'; //$worksheet->getHighestColumn(''); // e.g 'F'
$highestColumnIndex = PHPExcel_Cell::columnIndexFromString($highestColumn);
$nrColumns = ord($highestColumn) - 64;
//Echo file info
echo "<br>The worksheet ".$worksheetTitle." has ";
echo $nrColumns . ' columns (A-' . $highestColumn . ') ';
echo ' and ' . $highestRow . ' row.';
echo '<br>Data: <table border="1"><tr>';
//Loop threw colum, rows and cells
for ($row = 2; $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 = 2; $row <= $highestRow; ++ $row) {
$val=array();
for ($col = 0; $col < $highestColumnIndex; ++ $col) {
$cell = $worksheet->getCellByColumnAndRow($col, $row);
$val[] = $cell->getCalculatedValue();
}
// Prepare Query
$query = "INSERT INTO phpexcel(
objekt_nr,
objekt_rev,
element_nr,
element_hojd,
element_typ,
element_langd,
element_oppningar,
element_vikt,
element_ritare,
element_status)
VALUES (
:objekt_nr,
:objekt_rev,
:element_nr,
:element_hojd,
:element_typ,
:element_langd,
:element_oppningar,
:element_vikt,
:element_ritare,
:element_status
)";
// Security measures
$query_params = array(
':objekt_nr' => $val[0],
':objekt_rev' => $val[1],
':element_nr' => $val[2],
':element_hojd' => $val[3],
':element_typ' => $val[4],
':element_langd' => $val[5],
':element_oppningar' => $val[6],
':element_vikt' => $val[7],
':element_ritare' => $val[8],
':element_status' => $val[9]
);
try {
$stmt = $db->prepare($query);
$result = $stmt->execute($query_params);
}
catch(PDOException $ex){ die("Failed to run query: " . $ex->getMessage()); }
//echo $query."\n";
}
}
Two options here.
1) Make "objekt_nr" field a PRIMARY or UNIQUE key and use REPLACE instead of INSERT (http://dev.mysql.com/doc/refman/5.0/en/replace.html). This is pretty much #hd 's answer in the comments.
2) Check for an existing "objekt_nr" and "element_nr" and run the appropriate query
$check_duplicate_query = "SELECT COUNT(*) FROM phpexcel WHERE objekt_nr = ':objekt_nr' AND element_nr = ':element_nr'";
$stmt = $db->prepare($check_duplicate_query);
$result = $stmt->execute($query_params);
$rows = $stmt->fetch(PDO::FETCH_NUM);
if($rows[0] > 0) {
//UPDATE
} else {
//INSERT
}
$stmt = $db->prepare($query);
$result = $stmt->execute($query_params);
EDIT:
Just thought of a 3rd option
Create another field "objekt_element_nr" and set this field to unique.
This field gets assigned objekt and element number combination, which from your example should be unique.
e.g. 1_1, 1_2, 1_3, 2_1, 2_2, etc.
Then simply use the REPLACE function I linked to above.
Your $query_params would look like
$query_params = array(
':objekt_nr' => $val[0],
':objekt_rev' => $val[1],
':element_nr' => $val[2],
':objekt_element_nr' => $val[0].'_'.$val[2]
':element_hojd' => $val[3],
':element_typ' => $val[4],
':element_langd' => $val[5],
':element_oppningar' => $val[6],
':element_vikt' => $val[7],
':element_ritare' => $val[8],
':element_status' => $val[9]
);
this scripts reads and excel file and put them into a table and show them . the problem here is i want my data in cell to show green if they are above 0 and red if they are less than 0 this is my script and i dont know why it doesnt work !! every thing is fine untill line 53 !!wich i set if for val above 0 !! can any one help ?? thnkx in advance !!!
`
<?php
require 'Classes/PHPExcel.php';
require_once 'Classes/PHPExcel/IOFactory.php';
$conn = mysql_connect("localhost","datanew","datanew");
mysql_select_db("datanew",$conn);
$path = "1.xlsx";
$objPHPExcel = PHPExcel_IOFactory::load($path);
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 '<table><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 . '<br></td>';
}
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();
} }
?>
<?php
if($val > 0) {?>
<td style="color:#06e716;"></td>
<?php } else { ?>
<td style="color:#e70630;"></td>
<?php } ?>`
$val is an array, you need to use count function
try
if(count($val)>0){
}else{
}
so I'm trying to create an array from excel list using php
my excel has these values between A1:A3 - value1, value2, value3
My code is this:
<?php
require_once dirname(__FILE__) . '/includes/libraries/classes/PHPExcel.php';
$objPHPExcel = new PHPExcel();
$objReader = new PHPExcel_Reader_Excel5();
$objReader->setReadDataOnly(true);
$objPHPExcel = $objReader->load( dirname(__FILE__) . '/Tellimus.xls' );
$objWorksheet = $objPHPExcel->getActiveSheet();
$highestRow = $objWorksheet->getHighestRow(); // e.g. 10
$highestColumn = $objWorksheet->getHighestColumn(); // e.g 'F'
$highestColumnIndex = PHPExcel_Cell::columnIndexFromString($highestColumn); // e.g. 5
$newarray=array();
echo '<table>' . "\n";
for ($row = 1; $row <= $highestRow; ++$row) {
echo '<tr>' . "\n";
for ($col = 0; $col <= $highestColumnIndex; ++$col) {
$column=$objWorksheet->getCellByColumnAndRow($col,$row)->getValue();
echo '<td>' . $objWorksheet->getCellByColumnAndRow($col, $row)->getValue() . '</td>' . "\n";
$newarray[] = $column;
}
echo '</tr>' . "\n";
}
echo '</table>' . "\n";
print_r($newarray);
?>
And it shows as: Array ( [0] => value1 [1] => [2] => value2 [3] => [4] => value3 [5] => )
My goal is to get an array without having empty spaces as number 1 array and number 3 array and so on after every entry. How can I accomplish this?
hope this help:
<?php
require_once dirname(__FILE__) . '/includes/libraries/classes/PHPExcel.php';
$objPHPExcel = new PHPExcel();
$objReader = new PHPExcel_Reader_Excel5();
$objReader->setReadDataOnly(true);
$objPHPExcel = $objReader->load( dirname(__FILE__) . '/Tellimus.xls' );
$objWorksheet = $objPHPExcel->getActiveSheet();
$highestRow = $objWorksheet->getHighestRow(); // e.g. 10
$highestColumn = $objWorksheet->getHighestColumn(); // e.g 'F'
$highestColumnIndex = PHPExcel_Cell::columnIndexFromString($highestColumn); // e.g. 5
$newarray=array();
echo '<table>' . "\n";
for ($row = 1; $row <= $highestRow; ++$row) {
echo '<tr>' . "\n";
for ($col = 0; $col <= $highestColumnIndex; ++$col) {
$column=$objWorksheet->getCellByColumnAndRow($col,$row)->getValue();
echo '<td>' . $objWorksheet->getCellByColumnAndRow($col, $row)->getValue() . '</td>' . "\n";
if (isset ($column)){
$newarray[] = $column;
}
}
echo '</tr>' . "\n";
}
echo '</table>' . "\n";
print_r($newarray);
?>
i am trying to insert excel sheet into mysql DB using PHPEXCEL , i am beginner to php PDO , i am using the code below :
<?PHP
if (isset($_FILES["file"]))
{
$info_file_exts = array("csv", "xls", "xlsx");
$info_upload_exts = end(explode(".", $_FILES["file"]["name"]));
if ((($_FILES["file"]["type"] == "Excel/csv")
|| ($_FILES["file"]["type"] == "Excel/xls")
|| ($_FILES["file"]["type"] == "Excel/xlsx")
)
&& in_array($info_upload_exts, $info_file_exts))
if ($_FILES["file"]["error"] > 0)
{
echo "Return Code: " . $_FILES["file"]["error"] . "<br>";
}
else
{
$info_file_exts = array("csv", "xls", "xlsx");
if($info_file_exts[0]=='csv'){
$ink=explode('.'.$info_file_exts[0],$_FILES["file"]["name"]);
$time=time();
$info_new_file_name =$ink[0].'_'.$time.'.'.$info_file_exts[0];
}
else if($info_file_exts[1]=='xls')
{
$ink=explode('.'.$info_file_exts[1],$_FILES["file"]["name"]);
$time=time();
$info_new_file_name =$ink[0].'_'.$time.'.'.$info_file_exts[0];
}
else if($info_file_exts[2]=='xlsx')
{
$ink=explode('.'.$info_file_exts[2],$_FILES["file"]["name"]);
$time=time();
$info_new_file_name =$ink[0].'_'.$time.'.'.$info_file_exts[0];
}
}
$path = ($_FILES["file"]["tmp_name"]);
$objPHPExcel = PHPExcel_IOFactory::load($path);
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 "File ".$worksheetTitle." has ";
echo $nrColumns . ' columns';
echo ' y ' . $highestRow . ' rows.';
echo 'Data: <table width="100%" cellpadding="3" cellspacing="0"><tr>';
for ($row = 1; $row <= $highestRow; ++ $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 = 2; $row <= $highestRow; ++$row)
{
$val=array();
for ($col = 0; $col < $highestColumnIndex; ++ $col)
{
$cell = $worksheet->getCellByColumnAndRow($col, $row);
$val[] = $cell->getValue();
}
$email=$val[0];
$pass= $val[1];
$sql="insert into users (email, password) VALUES (:email,:pass)";
$q = $conn->prepare($sql);
$q->execute(array(':email'=>$email,':pass'=>$pass));
}
?>
<div style="width: 500px; margin: 200px auto 0 auto;">
<form action="display.php" method="post" enctype="multipart/form-data" >
<label for="file">Filename: </label>
<input type="file" name="file" id="file"><br>
<input type="submit" name="submit" value="Submit" style="margin-left:90PX">
</form>
</div>
this code works fine , but i want to do is to count how many rows are added? , i try to use rowCount() function but it return the output for each insert , i want to use it with all the insert task, another thing an error shows if the user click the submit button more than one time how can i fix that ?