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 ?
Related
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.
I want a gallery of uploaded images, showing 4 images each tr.
There needs to be a loop somewhere but I can't get it to work.
It needs to add a tr automatically when there are 4 images in a tr.
<?php
$folder = 'uploads/';
$filetype = '*.*';
$files = glob($folder.$filetype);
$count = count($files);
$sortedArray = array();
for ($i = 0; $i < $count; $i++) {
$sortedArray[date ('YmdHis', filemtime($files[$i]))] = $files[$i];
}
krsort($sortedArray);
echo '<table>';
foreach ($sortedArray as &$filename) {
echo '<td align="center">';
echo '<a name="'.$filename.'" href="#'.$filename.'"><img src="'.$filename.'" /></a>';
echo 'Bestand naam: ' . substr($filename,strlen($folder),strpos($filename, '.')-strlen($folder));
echo '</td>';
}
echo '</table>';
?>
Let a counter, say $i run alongside your foreach loop that ticks up by one every time the loop ran. Check for "every fourth element" with if ($i % 4 ==0)
Use a counter in your loop. It should look like this :
echo '<table>';
$ctr = 0;
foreach ($sortedArray as &$filename) {
echo ($ctr % 4 == 0) ? "<tr>" : "";
echo '<td align="center">';
echo '<a name="'.$filename.'" href="#'.$filename.'"><img src="'.$filename.'" /></a>';
echo 'Bestand naam: ' . substr($filename,strlen($folder),strpos($filename, '.')-strlen($folder));
echo '</td>';
$ctr++;
echo ($ctr % 4 == 0) ? "</tr>" : "";
}
echo '</table>';
<?php
$folder = 'uploads/';
$filetype = '*.*';
$files = glob($folder . $filetype);
$count = count($files);
$sortedArray = array();
$i = 0;
krsort($sortedArray);
echo '<table><tr>';
foreach($sortedArray as & $filename)
{
echo '<td align="center">';
echo '<a name="' . $filename . '" href="#' . $filename . '"><img src="' . $filename . '"/> </a>';
echo 'Bestand naam: ' . substr($filename, strlen($folder) , strpos($filename, '.') - strlen($folder));
echo '</td>';
if ($i % 4 == 0)
{
echo '</tr><tr>';
}
$i++;
}
echo '</tr></table>';
?>
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{
}
CODE:
<?php
$page = $_GET['page'];
$category = $_GET['cat'];
$your_db = # new mysqli("database","name","password");
if (mysqli_connect_errno())
{
echo 'ERROR!
'.mysqli_connect_errno()
.' - Not connected : '.mysqli_connect_error().'
';
die;
}
else
{
$db_connect = $your_db->select_db("databasename");
if (!$db_connect)
{
echo 'ERROR CONNECT DATA BASE';
die;
}
}
echo '<p>';
$query = "select distinct fldCity from info order by fldCity";
$result = $your_db->query($query);
$number_of_records = $result->num_rows;
for ($i = 0; $i < $number_of_records; $i++)
{
$row = $result->fetch_assoc();
echo '<a href="index.php?cat='.stripslashes($row['fldCity']).'">';
echo stripslashes($row['fldCity']);
echo '</a> / ';
}
echo '</p>';
if ($category)
{
$query = "select fldCompanyLogo, fldCompanyName, fldAddress, fldCity, fldProvince, fldPostalCode, fldMenuLink
from info where fldCity = '$category' and length(fldCompanyLogo) > 0 order by fldCity";
}
else
{
$query = "select fldCompanyLogo, fldCompanyName, fldAddress, fldCity, fldProvince, fldPostalCode, fldMenuLink
from info where length(fldCompanyLogo) > 0 order by fldCity";
}
$result = $your_db->query($query);
$number_of_records = $result->num_rows;
$num_pages = $number_of_records / 7;
if (($number_of_records % 7) > 0 )
{
$num_pages++;
}
if (strlen($page) == 0)
{
$page = 0;
}
else
{
$page = $page * 4;
}
echo '<table border="0" cellspacing="10" cellpadding="10" style="border-collapse: collapse" bordercolor="#111111">';
$row_num = 4;
$result->data_seek($page);
for ($i = $page; $i < $number_of_records; $i++)
{
if ($row_num <= 4)
{
echo '<tr>';
for ($col_num = 0; $col_num < 4; $col_num++)
{
$row = $result->fetch_assoc();
echo '<td>';
show_image(stripslashes($row['fldCompanyLogo']),stripslashes($row['fldCompanyName']));
echo '
';
echo '<b><font face="Tahoma" size="2"><a href="mysite.ca/'.stripslashes($row['fldMenuLink']).'" target="_blank"></font>';
echo '<font face="Tahoma" size="2"><a href="'.stripslashes($row['fldMenuLink']).'" target="_blank">';
echo stripslashes($row['fldCompanyName']);
echo '</a>';
echo '
';
echo stripslashes($row['fldCity']);
echo '
';
echo stripslashes($row['fldProvince']);
echo '
';
echo stripslashes($row['fldPostalCode']);
echo '</td>';
}
$row_num++;
echo '</tr>';
}
else
{
break;
}
}
echo '</table>';
for ($j = 0; $j < $num_pages; $j++)
{
$page_link = $j + 1;
echo '<font face="Tahoma" size="4"><b>'.$page_link.'</b></font> ';
}
echo ' '.$number_of_records;
function show_image($image_name)
{
if (file_exists("'$image_name'"))
{
$dim_img = getimagesize('/images/'.$image_name);
echo '<img src="/images/'.$image_name.'" alt = '.$alt.' border=0 align="bottom"';
echo 'width = '. $dim_img[100] .' height = ' .$dim_img[100] . ' />';
}
else
echo 'Add your image here!';
}
?>
I am totally lost and I can't find the error to why the images from the database isn't loading with the script. I highlighted the area in blue where I believe the error is to be. I just can't find any errors in that particular spot! All I want is the images from a column I have in my database to be fetched and connected to 'echo '
No images are being displayed, and I can't find the error as to why the images aren't showing up
try Convert Image to Base64 String and Base64 String to Image
also why echo ''; you use this its makes no sense
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>';
}
}
?>