i have 150 rows and 40 columns in a sql table..i am displaying the entire table in a web page..now,what i want to do is create a link on that web page that will take the entire table and insert it in an excel file(dosn't matters if it creates a new excel file,or modifies sum exisiting one)...now i can do it manually by using(PHPExcel library)," objPHPExcel->setCellValue('C5', $v) "...but i would have to write this like 40 times(change '$v' variable in every statment) nd its inside a loop that will run 150 times..hence i dont wanna do it this way..
now i wanted to know if i can insert the table,row by row in the excel sheet..like when i insert a row,it will insert the entire cells of d row..that way it will be pretty easy..so i wanted to know if there any specific commands for doing this..
if not,wat other alternatives do i have of doing this..all i want to do is to export the entire sql table to an excel file using php..
So use the fromArray() method that PHPExcel thoughtfully provides that allows you to write a whole row or whole block of cells in one call from an array.
Looking at the examples and reading the documentation always helps
Additional note
Incidentally, $objPHPExcel->setCellValue('C5', $v) will only work if $objPHPExcel is a worksheet, most of the examples use $objPHPExcel for the workbook (ie the collection of worksheets) so don't get confused
EDIT
For fetching the results from your database, use
sqlsrv_fetch_array($tsql, SQLSRV_FETCH_ASSOC)
or
sqlsrv_fetch_array($tsql, SQLSRV_FETCH_NUMERIC)
EDIT 2
Check how the database is set to handle NULL returns; but using
$objPHPExcel->getActiveSheet()->fromArray($rows, 0, 'A'.$rowCNT);
should set all NULL values from the database result to 0 value in PHPExcel
The easiest way is to export a .csv file, which can also be read by excel.
All you have to do is create this page :
<?
header("Content-type: application/csv");
header("Content-Disposition: attachment; filename=file.csv");
header("Pragma: no-cache");
header("Expires: 0");
$link = mysql_connect('db', 'dblogin', 'dbpasswd');
#mysql_select_db('dbname') or die( "Unable to select database");
$query=mysql_query("SELECT * FROM whatever");
$j=0;
$nbField = mysql_num_fields($query);
while ($j < $nbField) {
echo mysql_field_name($query,$j).";";
$j++;
}
echo "\n";
while ($row = mysql_fetch_array($query, MYSQL_NUM)) { echo implode(";", $row)."\n"; }
?>
Then you insert a link pointing directly to this php page, it will download the csv file.
Related
I wrote a PHP script that generates XLs files from SQL queries on MariaDB using PhpSpreadSheet.
It works really fine most of the time, but I've got issues with my biggest extract: Excel tells me (when I try to open the files) that it is "corrupted". If I skip the alert and open it, all the expected rows are in the file (my Mac users can't open it at all).
Here are the results of my investigations and observations:
- for one given query, I can set a SQL "LIMIT" (max number of rows) to have a non-corrupted file again. For one given query, this LIMIT between ok and not-corrupted and corrupted files will always be the same number.
- for one given query, this "LIMIT" between corrupted and not corrupted files will be pretty much the same whether the IDs are sort ASCendig or DESCending (in the SQL query. This way, suppose it's not a specific character in one row that breaks the file. This conclusion is validated by the fact that if I exclude the rows around this limit, the problem remains. However, if I replace each value to be written in the cells of the XLs file by a big random string ("abcdefghijklm", slightly bigger than the average length of each cell from my request), the problem disappears.
I'm using PHP V7.0.33 (memory_limit 1024M) / Ubuntu16.04.1 / MariaDB.
There is no memory limit warning in the Apache2/log/error.log (no error at all)
<?php
//Initialization
require '/var/www/html/vendor/autoload.php';
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xls;
ob_clean();
//Getting data from DB
$connect = mysqli_connect("localhost", "user", "pass", "base","port");
$query = "SELECT * FROM ... WHERE ...";
$result = mysqli_query($connect, $query);
$filename="...";
//If data exist
if(mysqli_num_rows($result) > 0){
$spreadsheet = new Spreadsheet(); /*----Spreadsheet object-----*/
$Excel_writer = new Xls($spreadsheet); /*----- Excel (Xls) Object*/
$spreadsheet->setActiveSheetIndex(0);
$activeSheet = $spreadsheet->getActiveSheet();
$first = true;
$irow=0;
//Loop on each row
while($row = mysqli_fetch_array($result,MYSQLI_ASSOC)){
//Headers
if ($first) {
$irow++;
$icol=0;
foreach (array_keys($row) as &$value) {
$icol++;
$activeSheet->setCellValueByColumnAndRow( $icol,$irow, $value );
}
$first = false;
}
//DataBodyRange
$irow++;
$icol=0;
foreach (($row) as &$value) {
$icol++;
$activeSheet->setCellValueByColumnAndRow( $icol,$irow, $value );
}
}
//Finalizartion
header('Content-Type: application/vnd.ms-excel');
header('Content-Disposition: attachment;filename="'.$filename.'"');
header('Cache-Control: max-age=0');
$Excel_writer->save('php://output');
}
?>
Romain Dub,
I had pretty much the same problem.
Mine was slightly reversed. I wanted an xlsx but kept getting the error as you were. After my spreadsheet was created, I changed the extension to xls and I got the spreadsheet to open and when it opened, I found lines in the spreadsheet about a couple of undefined variables. If you need to resolve your error, possibly check your code for undefined variables being inserted into your spreadsheet.
Just an idea that may or may not be the solution to your problem.
This method for exporting data on csv has worked previously on other projects, but I can not make this work on here, and I am not sure about how to enable erros for this case.
This PHP file creates a comma-separated file containing an initial row with a single tab ("ID"), and then it should be creating a row for each match on the SELECT query from DB
<?php
session_start();
ob_start();
include('conexionbbdd.php');
$file='informes/expositores_'.time().'.xls';
header("Content-Type: application/xls");
header("Content-Disposition: attachment; filename=$file");
header("Pragma: no-cache");
header("Expires: 0");
$output = fopen($file, 'w');
fwrite($output, chr(239) . chr(187) . chr(191));
fputcsv($output, array('ID'), "\t");
// fetch the data
$rows1 = mysqli_query($con, "SELECT ex_id FROM expositores WHERE ex_id = '26'");
// loop over the rows, outputting them
while ($row1 = mysqli_fetch_assoc($rows1)) {
fputcsv($output, $row1, "\t");
}
fclose($output);
echo $file;
ob_end_flush();
?>
In this particular case I've simplified this to maximu so, apart from the initial row, a unique row containg the "26" should be created (I've tested that the query works with PhpMyAdmin, there's an ID 26). But it does not.
It only creates correctly first row from this first fputcsv method:
fputcsv($output, array('ID'), "\t");
No other row seems to be fetched or placed on the CSV.
As the entire PHP file's aim is to create the CSV file, no error is shown because it does not open on a new window.
Output:
In order to solve this you will need to be able to view the errors. You can have a look in your error logs or add error reporting to the top of your file(s) right after your opening <?php tag error_reporting(E_ALL); ini_set('display_errors', 1);
I want to download a file which includes the results of my mysql query but my problem is, the .txt file includes only the last result of my mysql query. It should includes actually 5 results like this:
http://user:password#server.com:8080
Can someone show me where here the problem is?
<?php
$result = mysql_query("SELECT serverurl FROM ibn");
echo mysql_error();
while ($row = mysql_fetch_array($result)) {
$result2 = mysql_query("SELECT streamport,streamname FROM streams");
echo mysql_error();
while ($row2 = mysql_fetch_array($result2)) {
$result3 = mysql_query("SELECT client_username,client_openpasswd FROM clients WHERE `client_id` = '$id' ");
echo mysql_error();
while ($row3 = mysql_fetch_array($result3)) {
$streamurl= $row['serverurl'];
$streamport = $row2['streamport'];
$streamuser= $row3['client_username'];
$streampassword= $row3['client_openpasswd'];
$streamchannel= $row2['streamname'];
echo "<p>http://$streamuser:$streampassword#$streamurl:$streamport</p>";
}
}
}
//Generate text file on the fly
header("Content-type: text/plain");
header("Content-Disposition: attachment; filename=bouquet.txt");
?>
Your basic output can be achieved by moving your calls to header() to the top of the script and emitting your data later. The header commands will only be effective if they're issued before any output is sent to the client.
You can demonstrate this with a simple script:
<?php
header("Content-type: text/plain");
header("Content-Disposition: attachment; filename=bouquet.txt");
echo "A line of text\n";
The remainder of your code is more problematic. It's not clear why you're doing this, but the effect of your code is to produce the cartesian product of the three tables. i.e. every row in every table is combined with every row in every other table. I doubt this is actually what you want, but...
You can achieve the same result more efficiently by using an SQL JOIN with no ON clause. Using that and concatenating the required fields you can do almost everything you want in a single SQL query:
select
concat('http://',
clientname,':',
clientopenpassword,'#',
serverurl,':',
streamsport)
as URL
from ibn, streams, clients where client_id=1
I'll leave converting this to a working PHP script as an exercise for the reader, but your code above provides a good template. Remember, only one query and one loop to fetch the result and emit it.
Note that mysql_*() is deprecated - use mysqli_*() for new code. You should also watch for possible SQL injection where you use $id in your query.
So, I have searched most of the answers here on stack and google and anywhere I could think of. There are plenty of answers indeed, but none have the structure I need.
Al my code looks like this:
$sql = "SELECT * FROM users WHERE user_level = '$level' ORDER BY user_username DESC";
if ($stmt = $this->connect->prepare($sql)) {
$stmt->bind_result($id);
$stmt->execute();
while ($row = $stmt->fetch()) {
$stmt->bind_result($id);
$users[] = $id;
}
$stmt->close();
$length[] = sizeof($users);
} else {
$error = true;
$message['error'] = true;
$message['message'] = CANNOT_PREPARE_DATABASE_CONNECTION_MESSAGE;
return json_encode($message);
}
I'm using mysqli and stmt in all of my code, so I would like to keep it like this all the way.
So, I understand that I cannot have the CSV file where I have my action button to download it. But the thing is that my action button is part of a form, so I guess that instead of $_GET on the page I have the CSV I will have $_POST.
And my question, how do I loop through all database ( this needs to be depending on a column, a level ) and take all that data organized in a CSV file and than download it ? But this needs to be as the structure I have for my functions, I don't want to use db_query("SELECT * FROM {loreal_salons}"); per say or other like that.
Use the following :
// Setup the headers to force download of CSV
header("Content-type: application/csv");
header("Content-Disposition: attachment; filename=file.csv");
header("Pragma: no-cache");
header("Expires: 0");
// loop your records here and output as comma separated
echo $row['col1'].",".$row['col3'].",".$row['col3']."\n";
If you want to loop over all the database, I think the key for what you want to do is :
SHOW TABLES - http://dev.mysql.com/doc/refman/4.1/en/show-tables.html
.. to loop in all the tables
SHOW COLUMN - http://dev.mysql.com/doc/refman/5.0/en/show-columns.html
.. to loop in all the column of a specific table
I am using spreadsheet_excel_writer(9.2) to download an excel file from a mysql (4.1.22) database. I have done this successfully on the same server, and this code is very similar, but on this occasion it isn't working. I get an excel file that has the data in it but all in one cell with all sorts of characters intermingled. Does anyone have any idea what the problem could be? I have been making alterations and re-testing for days now. I would really appreciate it if someone could spot something that I am not seeing.
<?php
require_once "/home/cloudare/php/Spreadsheet/Excel/Writer.php";
// Create workbook
$workbook =& new Spreadsheet_Excel_Writer();
// sending HTTP headers
$workbook->send('registration.xls');
// Create worksheet
$worksheet =& $workbook->addWorksheet('Registration Worksheet');
// Add DB connection script here
include("dbinfo.inc.php");
include("functions.inc.php");
$from=$_POST['from'];
$to=$_POST['to'];
mysql_connect(localhost,$username,$password);
#mysql_select_db($database) or die( "Unable to select database");
$query = "SELECT * FROM register WHERE date BETWEEN '$from' AND '$to'" ;
$result = mysql_query($query);
//$result = do_query($query,__LINE__);
// Loop through the data, adding it to the sheet
while($row = mysql_fetch_assoc($result))
{
$array[] = $row;
extract($row);
$worksheet->write($currentRow,0,$id);
$worksheet->write($currentRow,1,$name);
$worksheet->write($currentRow,2,$last);
$worksheet->write($currentRow,3,$title);
$worksheet->write($currentRow,4,$company);
$worksheet->write($currentRow,5,$phone);
$worksheet->write($currentRow,6,$mobile);
$worksheet->write($currentRow,7,$email);
$worksheet->write($currentRow,8,$cloud);
$worksheet->write($currentRow,9,$participant);
$worksheet->write($currentRow,10,$date);
// Remember Excel starts counting rows from #1!
$excelRow = $currentRow + 1;
$currentRow++;
}
$workbook->close();
?>
This is the resultant worksheet:
ÐÏࡱá;þÿ
þÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿ
s#Gert
MrClann
Credogert#clanncredo.ie
2011-06-17°s#Jim
MaherDirectorTrigraph
01-6390050087-6261422jim#trigraph.ieð?
2011-06-17Às#MichaelMcKennaPrincipal
Consultant
SmartCloud#ì̘TBmmckenna#smartcloud.ieð?
2011-06-17Ðs#LiamConnolly
ConsultantCapricornVentis6¦ÊA#liam.connolly#capventis.comð?
2011-06-17às#MinhajShaikh
MrNCIapnaminhaj#hotmail.comð?
2011-06-17> ¶ Root
Entryÿÿÿÿÿÿÿÿ ÿÿÿÿÿÿÿÿÿÿÿÿ
S_E_W is deadware. You should switch to PHPExcel at some point, especially if you want support for something newer than BIFF 5.0 files (Excel 5.0).
Check that your query is working correctly and produces a proper $row. And try to avoid extract() like the plague. It's almost as horrible an idea as register_globals was and lets you reproduce the exact same problems that register_globals caused in the first place. It's not much more work to type out $row['id'], $row['name'] etc..., and saves you the annoyance of overwriting other variables you were using for other purposes BEFORE doing the extract() call.