how to set conditional css in php - php

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{
}

Related

Skip row if more than one cell is empty with PHP

I have a PHP script that generates an HTML table from a CSV file.
Right now if any cells are missing information, it skips the row. HOWEVER, I'd prefer if it skipped a row if more than one cell was missing. So if a row has 2 empty cells, it should skip.
I have marked it //edit here below but unsure how to acheive this.
<?php
$idsColumnsWanted = array(0,1,8,19);
echo "<table class='table table-bordered' id='example'>\n\n";
$f = fopen("users.csv", "r");
$first_line = false;
while (($line = fgetcsv($f)) !== false) {
// Restart column index
$i = 0;
$row ="";
if($first_line == false) {
$row = "<thead><tr>";
$col = "th";
} else {
$row = "<tr>";
$col= "td";
}
$is_empty = false;
foreach ($line as $i => $cell) {
// Skips all columns not in your list
if (! in_array($i, $idsColumnsWanted)) continue;
// edit here
if ($cell !== '') {
$row .= "<".$col.">" . htmlspecialchars($cell) . " </".$col.">";
} else {
$is_empty = true;
}
// Increase index
$i++;
}
if($first_line == false)
$row .= "</tr></thead>";
else
$row .= "</tr>";
$first_line = true;
if ($is_empty) {
continue;
} else {
echo $row;
}
}
fclose($f);
echo "\n</table>";
?>
please try this code
$is_empty = false;
$count = 0;
$countlimit = 2; // define empty cell limit here
foreach ($line as $i => $cell) {
// Skips all columns not in your list
if (!in_array($i, $idsColumnsWanted))
continue;
// edit here
if($cell==""){
$count++;
}
if ($count <= $countlimit) {
$row .= "<" . $col . ">" . htmlspecialchars($cell) . " </" . $col . ">";
} else {
$is_empty = true;
break;
}
}
You have to cound how many cells are empty in a row. To do so init the counter for each line.
$empty_cells = 0; //Init with 0 for each line
foreach ($line as $i => $cell) {
// Skips all columns not in your list
if (! in_array($i, $idsColumnsWanted)) continue;
// edit here
if ($cell !== '') {
$row .= "<".$col.">" . htmlspecialchars($cell) . " </".$col.">";
} else {
$empty_cells++; //count how many empty cells you have.
}
// Increase index
$i++;
}
and after that check if there are more than two empty cells like this:
if ($empty_cells >= 2) {
continue;
} else {
echo $row;
}

Failed to run query: 1048 Column 'element_oppningar' cannot be null

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.

PHP check if value exists

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]
);

count the number of rows inserted using PHPEXCEL

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 ?

Adding an Extra Empty Column While Reading An .xlsx file in PHP

I edited a PHP code that reads an Excel Spreadsheet (.xlsx form) and displays it very well.
But I want an extra column to be added when PHP page displays the Spreadsheet. (For textareas to update one cell in each row.)
What can I do for it?
Thanks.
<?php
if((!empty($_FILES["file"])) && ($_FILES['file']['error'] == 0)) {
$limitSize = 15000000;
require_once "simplexlsx.class.php";
$getWorksheetName = array();
$xlsx = new SimpleXLSX( $_FILES['file']['tmp_name'] );
$getWorksheetName = $xlsx->getWorksheetName();
echo ' <hr>
<div id="datacontent">
';
'<div id="datacontent">';
for($j=1;$j <= $xlsx->sheetsCount();$j++){
echo '<h3>Tablodaki Worksheet: '.$getWorksheetName[$j-1].'</h1>';
echo '<table id="xlsxTable">';
list($cols,) = $xlsx->dimension($j);
foreach( $xlsx->rows($j+1) as $k => $r) {
if ($k == 0){
$trOpen = '<th';
$trClose = '</th>';
$tbOpen = '<thead>';
$tbClose = '</thead>';
}else{
$trOpen = '<td';
$trClose = '</td>';
$tbOpen = '<tbody>';
$tbClose = '</tbody>';
}
echo $tbOpen;
echo '<tr>';
for( $i = 0; $i < $cols; $i++)
echo $trOpen.'>'.( (isset($r[$i])) ? $r[$i] : ' ' ).$trClose;
echo '</tr>';
echo $tbClose;
}
echo '</table>';
}
}
?>

Categories