Php to Excel : fill the output Excel file with a loop - php

I want to create an Excel file (with PhpExcel) and fill it with the content of a MySQL query.
I only have one column so the result will look like this :
$sheet->setCellValueByColumnAndRow(0, $i, $content)
So I have to loop inside my query and create a counter to fill each row corresponding to each item of the column ptlum of my content.
So the goal is to have the following result :
1 AX001
2 AX003
3 AX012
The code is the one :
$column = 1;
while($data = mysql_fetch_assoc($result)) {
$workbook = new PHPExcel;
$sheet = $workbook->getActiveSheet();
$sheet->setCellValueByColumnAndRow(0, $column, $data['ptlum']);
//echo($column. " " . $data['ptlum']. " ");
$column = $column + 1; //or $column++;
The problem is that my Excel file is empty..
If i put a number instead of $column in the setCellValueByColumnAndRow line it works. But the variable does not work..
On the other hand if I put "$column = 1;" inside the loop, my Excel file will always contain one only row..
Have you an idea ?
Thank you very much !

You just have to change the call to setCellValueByColumnAndRow for each column and increment it:
$sql = "SELECT ptlum FROM `ptlum` WHERE nomcom = 'AIGREFEUILLE' and RIGHT (date,4) < 2015 and RIGHT(date,4) > 0 ";
$result = mysql_query($sql);
$row = 1; // 1-based index
$column = 1;
while($data = mysql_fetch_assoc($result)) {
$sheet->setCellValueByColumnAndRow($column, $row, $data['ptlum']);
$column = $column + 1; //or $column++; if you prefer
}
As you see, you can retrieve the field/column you want with mysql_fetch_assoc, returning an associative array.
Also, you don't have to include the field(s) of your WHERE condition(s) in the SELECT.
Then finally, you should replace the deprecated mysql_* function by their equivalents mysqli_*, as explained here.
Edit:
For your "new" problem, this code should work:
$sql = "SELECT ptlum FROM `ptlum` WHERE nomcom = 'AIGREFEUILLE' and RIGHT (date,4) < 2015 and RIGHT(date,4) > 0 ";
$result = mysql_query($sql);
$row = 1; // 1-based index
$column = 1;
$workbook = new PHPExcel;
$sheet = $workbook->getActiveSheet();
while($data = mysql_fetch_assoc($result)) {
$sheet->setCellValueByColumnAndRow($column, $row, $data['ptlum']);
$column = $column + 1; //or $column++; if you prefer
}
First, don't instanciate your workbook and sheet in each loop, do it before, once.
Second, you had your arguments in the wrong order, it's column then row, not the inverse, as explicited in the method name.

Maybe this is the thing you wanted:
$sql = "SELECT ptlum, RIGHT(date,4) FROM `ptlum` WHERE nomcom = 'AIGREFEUILLE' and RIGHT (date,4) < 2015 and RIGHT(date,4) > 0 ";
$result = mysql_query($sql);
$i = 0;
while($data = mysql_fetch_assoc($result)) {
$sheet->setCellValueByColumnAndRow(0, $i, $i+1); //1-based index
$sheet->setCellValueByColumnAndRow(1, $i, $data['ptlum']);
$i++;
}

Related

I need a counter within a counter

I have searched for this, can't find it and it should be simple, but now I'm crosseyed. Forgive me - I've only been at this for a few months.
I need a counter within a counter in php, such that I pair $Id1 with $Id2, then $Id3, then $Id4, etc. for a single loop through, and then for the second loop pair $Id2 with $Id3, then $Id4, then $Id5 etc. I get the Ids from a sql query, then I use both of them to run a calculation of their relationship, but first I just need the structure to run these two loops, one within the other. Thanks for any help and your patience.
Edited to add what I have so far:
$collection = [];
$sql = 'SELECT id, name FROM table';
$result = mysql_query($sql);
while($row = mysql_fetch_assoc($result))
{
$collection[] = $row;
}
$ct = count($collection);
for ($i = 0; $i < $ct; $i++)
{
$Id1 = $collection[$i]['id'];
for ($j = 0; $j < $ct; $j++)
{
$Id2 = $collection[$j]['id'];
if($Id1 != $Id2){
echo 'IDs: ' . $Id1 . ' ' . $Id2 . '<br>';
}
}
}
}
If you fetch the IDs from your query into an array like this: $ids = [1,2,3,4,5,6,7,8];, you can get a list of pairs using array_chunk, then shifting off the first element, and repeating this process until the array is empty.
while ($ids) { // repeat until empty
$pairs = array_chunk($ids, 2); // split into pairs
foreach ($pairs as $pair) {
if (count($pair) == 2) { // verify that you have a pair (last element will
// have only one item when count($ids) is odd)
var_dump($pair); // do something with your pair of IDs
}
}
$remove_first = array_shift($ids); // shift off the first ID
}
Please note that using array_shift like this will destroy your input array, so if you need to do something else with it as well, make a copy of it before using this approach.

PHPExcel loop through rows and columns

Need help identifying weird problem that i'm facing. I did tried searching in stack overflow but didn't find any possible answer.
Here is sample program that works displaying all rows and columns on UI
<?php
date_default_timezone_set('America/Los_Angeles');
require_once 'PHPExcel-1.8/Classes/PHPExcel.php';
include 'PHPExcel-1.8/Classes/PHPExcel/IOFactory.php';
$path = 'demo.xlsx';
$sheet = $objPHPExcel->getSheet(0);
$highestRow = $sheet->getHighestRow();
$highestColumn = $sheet->getHighestColumn();
$highestColumnIndex = PHPExcel_Cell::columnIndexFromString($highestColumn);
for ($row = 2; $row <= $highestRow; ++ $row) {
$val=array();
for ($col = 0; $col < $highestColumnIndex; ++ $col) {
$cell = $worksheet->getCellByColumnAndRow($col, $row);
$val[] = $cell->getValue();
//End of For loop
}
$Col1 = $val[0] ;
$Col2 = $val[1] ;
$Col3 = $val[2];
echo $Col1;
echo $Col2;
echo $Col3;
echo "<br>";
//End of for loop
}
?>
This program works perfectly fine printing all columns and rows for n-lenght
Problem - Now our requirement is to get values of Col1, Col2, Col3 and using mysql_query compare into database and do further action.
Minute we add anything above //End of for loop. It only iterates once and stops without throwing any php errors.
e.g.
.....
echo $Col1;
echo $Col2;
echo $Col3;
echo "<br>";
**$sql = mysql_query("select COALESCE(MAX(SrNo), 0) AS Max_No from TABLEA where ColumnA = 1 and ColumnB = '$Col3'");
$row = mysql_fetch_array($sql);
echo $row["Max_No"];**
//End of for loop
}
?>
If we add above SQL the same program only iterates once and stops? It doesn't show any errors in logs or on screen.
Thanks in advance for your help!.
If you try to iterate with for ($col = 2; $col <= $highestColumn; ++ $col){...} it will work for columns from A to Z, but it fails pass the Z (Ex. iterate between 'A' to 'AB').
In order to iterate pass 'Z', you need to convert the column to integer, increment, compare, and get it as string again:
$MAX_COL = $sheet->getHighestDataColumn();
$MAX_COL_INDEX = PHPExcel_Cell::columnIndexFromString($MAX_COL);
for($index=0 ; $index <= $MAX_COL_INDEX ; $index++){
$col = PHPExcel_Cell::stringFromColumnIndex($index);
// do something, like set the column width...
$sheet->getColumnDimension($col)->setAutoSize(TRUE);
}
With this, you easy iterate pass the 'Z' column.
As you're using the same variable $row for the row number in the Excel iteration and for the result of your select query, it's not surprising that you're running into problems.....
The integer value that holds the Excel row number is being overwritten by the array that you get from your SQL query, and then you're trying to use that result array as the next Excel row number
Solution: Use a different variable for these two elements.
$rowData = mysql_fetch_array($sql);
echo $rowData["Max_No"];**

Get value from SQL database

I am trying to get a series of 'titles' from a database, and place them in an array as individual strings for each title. Currently I am using this code
mysql_select_db($database_Algorox_Build, $Algorox_Build);
$query_getLatest = "SELECT title FROM news ORDER BY title ASC";
$getLatest = mysql_query($query_getLatest, $Algorox_Build) or die(mysql_error());
$totalRows_getLatest = mysql_num_rows($getLatest);
$latestNews = array();
for ($i = 0; $i <= $totalRows_getLatest; ++$i) {
$row_getLatest = mysql_fetch_assoc($getLatest);
$latestNews[] = array_values($row_getLatest);
}
and when I call them individually using
echo $latestNews[0][0];
I get the string value.
However, I would like to place these strings in to a single array, thereby generating an array of strings. I have tried this:
$latestNews = array();
$extractNews = array();
for ($i = 0; $i <= $totalRows_getLatest; ++$i) {
$row_getLatest = mysql_fetch_assoc($getLatest);
$latestNews[] = array_values($row_getLatest);
$extractNews[] = $latestNews[i][0];
}
but it doesn't return the string in the output extractNews array.
What am I doing wrong?
Thanks
Is this what you are looking for?
mysql_select_db($database_Algorox_Build, $Algorox_Build);
$query_getLatest = "SELECT title FROM news ORDER BY title ASC";
$getLatest = mysql_query($query_getLatest, $Algorox_Build) or die(mysql_error());
$latestNews = array();
while($row = mysql_fetch_assoc($getLatest)) {
$latestNews[] = $row['title'];
}
echo "<pre>" . print_r($latestNews,1) . "</pre>";
WATCH OUT
Please do not use the mysql_* functions anymore. They are deprecated and won't be supported in >= php 5.5. Switch to mysqli_* or PDO.

php arrays and mysql query

This is driving me nuts! I need to fill up and HTML table with values that I pulled out from a DB.
The HTML table has 100 one td for each value.
I have an array that I populate doing this:
$x = 1;
$ArrayA = array();
for ($x = 1; $x <= 100; $x++) {
$ArrayA[$x] = 0;
}
So now I have an array with 100 values, right?
Then I query my DB, and get the result that I "want"
(select num from table1)
6 rows with the following values:
1,3,14,50,100.
Then I insert the values from my query into the $ArrayA that I populated before with one hundred 0's
$x = 1;
while ($row = mysql_fetch_array($result))
{
extract($row);
$ArrayA[$x] = "$num";
$x++;
}
Now $ArrayA has this:
1,3,14,17,100,0,0,0,0,0,0,0,0,0,0,0,0.....
And my goal is to replace with a 0 where I should have a "next" number, hard to explain..
I need this result:
1,0,3,0,0,0,0,0,0,0,0,0,0,14,0,0,17,0....
I tried to use PHP array_splice, but it did not work.
I tried with some if statements but my logic and programing experience is not that good.
Any suggestions?
Thanks
If i understand this right, you want to add a zero after every element returned by your query? Right? If so, why not add a zero right after you add an element into the array?
$x = 1; while ($row = mysql_fetch_array($result)) {
extract($row);
$ArrayA[$x] = "$num";
$x++;
$ArrayA[$x] = "0"; //adds zero after every $num insert
}
Maybe you can clarify if this isn't what you're asking...
$match_rows = mysql_fetch_array($result);
$rows = range(1,100);
foreach( $rows as $row){
echo '<td>';
if( in_array($row, $match_rows) ){
echo $row;
}else{
echo 0;
}
echo '</td>' . PHP_EOL;
}
Sorry, that is untested - it could be shorter or neater, but like that possibly illustrates another way of achieving what you want.
I think this is what you want for your second code block:
while ($row = mysql_fetch_array($result))
{
extract($row);
if($num > 0 && $ <= 100 )
{
$ArrayA[$num] = "$num";
}
}
If your DB values are 3, 10, 15, 22, 100, you'd end up with 0,0,3,0,0,0,0,0,0,10,0,0,0,0,15, etc etc.

PHPExcel Column Loop

How can I do a loop which based on Excel worksheet columns? I found (and used) WorksheetIterator, RowIterator and CellIterator but nothing about columns.
There is no ColumnIterator, so you'll have to do this by hand.
For any given worksheet:
To loop rows for a column:
$column = 'A';
$lastRow = $worksheet->getHighestRow();
for ($row = 1; $row <= $lastRow; $row++) {
$cell = $worksheet->getCell($column.$row);
// Do what you want with the cell
}
To loop columns in a row, you can take advantage of PHP's Perls-style ability to increment characters:
$row = 1;
$lastColumn = $worksheet->getHighestColumn();
$lastColumn++;
for ($column = 'A'; $column != $lastColumn; $column++) {
$cell = $worksheet->getCell($column.$row);
// Do what you want with the cell
}
Note that when comparing column letters to test for the last column in the loop, we can't simply use < or <= because we're comparing strings, and "B" > "AZ" in standard string comparison, so we use a != comparison, having incremented the highest column value to give the first column ID past the end point.
You can also use
$worksheet->cellExists($column.$row);
in the loop to test for the existence of a cell before accessing it using getCell() (or not) to emulate the iterator getIterateOnlyExistingCells() behaviour
The iterators are actually fairly slow, so you may well find these simple loops are faster than using the iterators.
UPDATE (2015-05-06)
PHPExcel version 1.8.1 has introduced a new Column Iterator. The Row and Column iterators also allows you to specify a range of rows or columns to iterate, and allow you to use prev() and well as next() when looping through
This short snippet provides loop throught rows of columns.
It gets the indexes of last non empty column (and its row) and loops to that indexes, so be aware of forgotten values in excel.
Code loops throught rows of column A, then rows of column B ...
$objReader = new PHPExcel_Reader_Excel2007();
$objReader->setReadDataOnly(true);
$objPHPExcel = $objReader->load($file);
foreach ($objPHPExcel->getWorksheetIterator() as $worksheet)
{
$worksheetTitle = $worksheet->getTitle();
$highestColumn = $worksheet->getHighestColumn();
$highestColumnIndex = PHPExcel_Cell::columnIndexFromString($highestColumn);
// expects same number of row records for all columns
$highestRow = $worksheet->getHighestRow();
for($col = 0; $col < $highestColumnIndex; $col++)
{
// if you do not expect same number of row records for all columns
// get highest row index for each column
// $highestRow = $worksheet->getHighestRow();
for ($row = 1; $row <= $highestRow; $row++)
{
$cell = $worksheet->getCellByColumnAndRow($col, $row);
$val = $cell->getValue();
// do what you want with cell value
}
}
}
loop columns as range
foreach ( range('A', $Excel->getActiveSheet()->getHighestColumn()) as $column_key) {
}
Try this! Work!
$limit = 10000;
$value='sua mensagem'
for($i=0,$j='A';$i<$limit;$i++,$j++) {
$objPHPExcel->setActiveSheetIndex(0)
->setCellValue($j.$i, $value);
}
set in $value what you want print.
This is the fix for the getColumnLetter method of the last message, it allows you to get the "letters" of the columns, whatever the number of columns you have
function getColumnLetter( $number ){
$prefix = '';
$suffix = '';
$prefNum = intval( $number/26 );
if( $number > 25 ){
$prefix = getColumnLetter( $prefNum - 1 );
}
$suffix = chr( fmod( $number, 26 )+65 );
return $prefix.$suffix;
}
This recursive method was designed allows you to get the "letters" of the columns, whatever the number of columns you have, from "A" to "ZZZZZZZZZ..." :
function getColumnLetter( $number )
{
$prefix = '';
$suffix = '';
$prefNum = intval( $number/26 );
if( $prefNum > 25 )
{
$prefix = getColumnLetter( $prefNum );
}
$suffix = chr( fmod( $number, 26 )+65 );
return $prefix.$suffix;
}
So you can loop the columns of an PHP array on index number and convert it to a string of letters and use it in PHPExcel methods, like "setCellValue" ...
But solutions above are surely faster if you can use them !
In PhpSpreadsheet ( which replaces PHPExcel ) you can do:
foreach( $sheet->getColumnIterator() as $col )
{
$sheet->getColumnDimension( $col->getColumnIndex() )->setAutosize( true );
}

Categories