download excel sheet from mysql database in php - php

I hve to download mysql database to excel sheet. I get following errors when i try to download
Notice: Undefined variable: data in C:\xampp\htdocs\admissions\excel\excel2.php on line 27
Notice: Undefined variable: header in C:\xampp\htdocs\admissions\excel\excel2.php on line 12.
What and where i need to define in header and data.
Here is the code
<?php
ob_start();
mysql_connect('localhost','root','');
mysql_select_db('sjbhsbg');
$sql = "SELECT * from admissions";
$res = mysql_query($sql) or die();
$count = mysql_num_fields($res);
// fetch table header from database
$header = '';
for ($i = 0; $i < $count; $i++){
$header .= mysql_field_name($res, $i)."\t";
}
// fetch data each row, store on tabular row data
while($row = mysql_fetch_row($res)){
$line = '';
foreach($row as $value){
if(!isset($value) || $value == ""){
$value = "\t";
}else{
$value = str_replace('"', '""', $value);
$value = '"' . $value . '"' . "\t";
}
$line .= $value;
}
$data .= trim($line)."\n";
$data = str_replace("\r", "", $data);
}
$name=date('d-m-y').'-list.xls';
header("Content-type:application/vnd.ms-excel;name='excel'");
header("Content-Disposition: attachment; filename=$name");
header("Pragma: no-cache");
header("Expires: 0");
// Output data
echo $header."\n\n".$data;
?>

$query="select * from admissions";
$result = mysql_query($query) or die('Please Choose any one of the fields to export');
//header('Content-Disposition: attachment;filename=export.csv');
$filename = $title.date("d-m-Y",time());
header('Content-Type: text/csv');
header("Content-disposition: csv" . date("Y-m-d") . ".csv");
header( "Content-disposition: filename=".$filename.".csv");
$row = mysql_fetch_assoc($result);
if ($row) {
echocsv(array($title));
echo "\r\n";
echocsv(array_keys($row));
}
while ($row) {
echocsv($row);
$row = mysql_fetch_assoc($result);
}
function echocsv($fields)
{
$separator = '';
foreach ($fields as $field) {
if (preg_match('/\\r|\\n|,|"/', $field)) {
$field = '"' . str_replace('"', '""', $field) . '"';
}
echo $separator . $field;
$separator = ',';
}
echo "\r\n";
}

Related

Need Help on Export SQL to CSV through PHP

I have this PHP script which is supposed to take an SQL Query and output it to a CSV file, I know that when I run it i'm getting the right Statement put in but it does not seem to generate a file to my uploads folder.
Could anyone debug this for me?
<?php
function ExportExcel($statement)
{
$filename = "uploads/".strtotime("now").'.csv';
$sql = mysql_query("$statement") or die(mysql_error());
$num_rows = mysql_num_rows($sql);
if($num_rows >= 1)
{
$row = mysql_fetch_assoc($sql);
$fp = fopen($filename, "w");
$seperator = "";
$comma = "";
foreach ($row as $name => $value)
{
$seperator .= $comma . '' .str_replace('', '""', $name);
$comma = ",";
}
$seperator .= "\n";
fputs($fp, $seperator);
mysql_data_seek($sql, 0);
while($row = mysql_fetch_assoc($sql))
{
$seperator = "";
$comma = "";
foreach ($row as $name => $value)
{
$seperator .= $comma . '' .str_replace('', '""', $value);
$comma = ",";
}
$seperator .= "\n";
fputs($fp, $seperator);
}
fclose($fp);
echo "<a href='$filename'>Download</a>";
echo $statement;
}
else
{
echo "error";
}
}
?>
If someone has a similar script that uses mysqli that would be nice
here is a example of a export script I use on my apps using MySqli. This will get you started...
<?php
function ExportExcel($statement){
$output = "";
$sql = mysqli_query($db , $statement);
$columns_total = mysqli_num_fields($sql);
// Get The Field Name
for ($i = 0; $i < $columns_total; $i++) {
$heading = mysqli_fetch_field_direct($sql, $i);
$output .= '"'.$heading->name.'",';
}
$output .="\n";
// Get Records from the table
while ($row = mysqli_fetch_array($sql)) {
for ($i = 0; $i < $columns_total; $i++) {
$output .='"'.$row["$i"].'",';
}
$output .="\n";
}
// Download the file
$filename = "CSV_NAME_GOES_HERE.csv";
header('Content-type: application/csv');
header('Content-Disposition: attachment; filename='.$filename);
echo $output;
exit;
}
?>

Exporting to CSV from MySQL via PHP

I am trying to bug fix a PHP script that should export values from a MySQL database to a CSV file.
The PHP file is returning a blank CSV file & I can't figure out why & I've been stuck on this for quite a while, so any help would be much apprwciated.
Code below:
<?
include('../../../inc/config.php');
$period = $_GET['pid'];
$psql = "SELECT month, year FROM survey_period WHERE sid = " . $period;
$pres = mysql_query($psql, $dcon);
$prow = mysql_fetch_array($pres);
$pmonth = $prow['month'];
$pyear = $prow['year'];
$query="SELECT
sid,
date,
stove_id,
name,
gender,
marital_status,
occupation_of_household,
cz_stove AS km_stove,
happy_with_cz_stove AS happy_with_km_stove,
cz_stove_in_use AS km_stove_in_use,
know_how_to_use,
FROM survey_usage WHERE period = " . $_GET['pid'];
$result = mysql_query($query, $dcon);
//header('Content-Disposition: attachment;filename=export.csv');
$filename = 'usage-'.$pid.'-'.$pmonth.'-'.$pyear;
header('Content-Type: text/csv');
header("Content-disposition: csv" . date("Y-m-d") . ".csv");
header( "Content-disposition: filename=".$filename.".csv");
$row = mysql_fetch_assoc($result);
if ($row) {
echocsv(array($title));
echo "\r\n";
echocsv(array_keys($row));
}
while ($row) {
echocsv($row);
$row = mysql_fetch_assoc($result);
}
function echocsv($fields)
{
$separator = '';
foreach ($fields as $field) {
if (preg_match('/\\r|\\n|,|"/', $field)) {
$field = '"' . str_replace('"', '""', $field) . '"';
}
echo $separator . $field;
$separator = ',';
}
echo "\r\n";
}
?>
hey i have a code you can use it like this
<?PHP
// Define database connection variable dynamically
$DB_Server = "localhost"; //MySQL Server
$DB_Username = "root"; //MySQL Username
$DB_Password = ""; //MySQL Password
$DB_DBName = "test1"; //MySQL Database Name
$DB_TBLName = "tabletest"; //MySQL Table Name
$filename = "excelfilename"; //File Name
//create MySQL connection
$sql = "Select * from csvtable";
$Connect = #mysqli_connect($DB_Server, $DB_Username, $DB_Password) or die("Couldn't connect to MySQL:<br>" . mysqli_error() );
//select database
$Db = #mysqli_select_db( $Connect,$DB_DBName) or die("Couldn't select database:<br>" . mysqli_error() );
//execute query
$result = #mysqli_query( $Connect,$sql) or die("Couldn't execute query:<br>" . mysqli_error() );
function cleanData(&$str)
{
if ($str == 't')
$str = 'TRUE';
if ($str == 'f')
$str = 'FALSE';
if (preg_match("/^0/", $str) || preg_match("/^\+?\d{8,}$/", $str) || preg_match("/^\d{4}.\d{1,2}.\d{1,2}/", $str)) {
$str = "'$str";
}
if (strstr($str, '"'))
$str = '"' . str_replace('"', '""', $str) . '"';
}
// filename for download
$filename = "file_" . date('Ymd') . ".csv";
header("Content-Disposition: attachment; filename=\"$filename\"");
header("Content-Type: text/csv;");
$out = fopen("php://output", 'w');
$flag = false;
while ($row = mysqli_fetch_assoc($result))
{
if (!$flag)
{
// display field/column names as first row
fputcsv($out, array_keys($row), ',', '"'); $flag = true;
}
array_walk($row, 'cleanData');
// insert data into database from here
fputcsv($out, array_values($row), ',', '"');
}
fclose($out);
exit;
//end
?>
The issue is that you are not writing anything to the csv file before opening it.
Use this code
$fp = fopen($filename, 'w');
$result = mysql_query($query);
$num_fields = mysql_num_fields($result);
$headers = array();
for ($i = 0; $i < $num_fields; $i++) {
$headers[] = mysql_field_name($result , $i);
}
fputcsv($fp, $headers);
while($row = mysql_fetch_assoc($result)) {
fputcsv($fp, $row);
}
fclose($fp);
header('Content-Type: text/csv');
header( "Content-disposition: filename=".$filename);
readfile($filename);
Thanks to everyone for your suggestions, problem now solved, turned out to be a simple comma in the wrong place - "know_how_to_use," changed to " know_how_to_use" solved the problem. Thanks #Tintu C Raju for pointing me in the right direction

send headers then refresh page?

I was asking earlier today about my database backup system
Here's the link: database backup system
Here is the code
if (isset($_POST['getbackup'])) {
/* setcookie("backupdisable", 1, time()*60*60*24); */
$db = "newsite";
$version = "2.3.1";
$date = date('Y-m-d H:i:s');
$final = "-- #".$version."#\n";
$final .= "-- database backup\n";
$final .= "--\n";
$final .= "-- PHP version: ".phpversion()."\n";
$final .= "-- MySQL version: ".mysqli_get_server_info($mysqli)."\n";
$final .= "-- Date: ".date("r")."\n";
$result = $mysqli->query("SHOW TABLE STATUS FROM ".$db);
while ($table = $result->fetch_array()) {
$i = 0;
$result2 = $mysqli->query("SHOW COLUMNS FROM $table[0]");
$z = $result2->num_rows;
$final .= "\n--\n-- DB Export - Table structure for table `".$table[0]."`\n--\n\nCREATE TABLE `".$table[0]."` (";
$prikey = false;
$insert_keys = null;
while ($row2 = $result2->fetch_array()) {
$i++;
$insert_keys .="`".$row2['Field']."`";
$final .= "`".$row2['Field']."` ".$row2['Type'];
if($row2['Null'] != "YES") { $final .= " NOT NULL"; }
if($row2['Default']) $final .= " DEFAULT '".$row2['Default']."'";
if($row2['Extra']) { $final .= " ".$row2['Extra']; }
if($row2['Key'] == "PRI") { $final .= ", PRIMARY KEY (`".$row2['Field']."`)"; $prikey = true; }
if($i < $z){
$final .= ", ";
$insert_keys .=", ";
}
else{
$final .= " ";
}
}
if($prikey) {
if($table[10]) $auto_inc = " AUTO_INCREMENT=".$table[10];
else $auto_inc = " AUTO_INCREMENT=1";
}
else $auto_inc = "";
$charset = explode("_", $table[14]);
$final .= ") ENGINE=".$table[1]." DEFAULT CHARSET=".$charset[0]." COLLATE=".$table[14].$auto_inc.";\n\n--\n-- DB Export - Dumping data for table `".$table[0]."`\n--\n";
$inhaltq = $mysqli->query("SELECT * FROM $table[0]");
while($inhalt = $inhaltq->fetch_array()) {
$final .= "\nINSERT INTO `$table[0]` (";
$final .= $insert_keys;
$final .= ") VALUES (";
for($i=0;$i<$z;$i++) {
$inhalt[$i] = str_replace("'","`", $inhalt[$i]);
$inhalt[$i] = str_replace("\\","\\\\", $inhalt[$i]);
$einschub = "'".$inhalt[$i]."'";
$final .= preg_replace('/\r\n|\r|\n/', '\r\n', $einschub);
if(($i+1)<$z) $final .= ", ";
}
$final .= ");";
}
$final .= "\n";
}
if($logged) {
header("Expires: 0");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Content-Type: application/force-download");
header("Content-Description: File Transfer");
if(is_integer(mb_strpos(strtolower($_SERVER["HTTP_USER_AGENT"]), "msie")) AND is_integer(mb_strpos(strtolower($_SERVER["HTTP_USER_AGENT"]), "win" ))) header("Content-Disposition: filename=backup-".strtolower(date("D-d-M-Y")).".sql;");
else header("Content-Disposition: attachment; filename=backup-".strtolower(date("D-d-M-Y")).".sql;");
header("Content-Transfer-Encoding: binary");
echo $final;
exit;
}
}
My question now is this :
The script works just fine, but now im trying to remove the submit button after you get this file so is this possible?
If i refresh the page the button will get removed but i dont know how to do so..
Because if i set a header that refreshes i can't download the file

Creating XLS file (Greek Characters)

I want to create a an XLS file with some info from the database and the data i want to retrieve from the database are all Greek characters.I have this code and when i execute the code i got only some symbols.Anyone knows what i have to change to get Greek characters properly?
Edit: The problem is both with the data that i retrieve from the Mysql Database and the headings
Here is the code
$sql = "SELECT tmima,sex,surname,address,postcode,phone1,phone2 FROM student"; //the query
$result = $db->prepare($sql);
$result->execute();
$column = $result->columnCount();
$header = "";
$head = array("Τμήμα","Φ","Επίθετο","Όνομα","Μητρώο"); //headings of the XLS
for($i = 0; $i < $column;$i++ ){
$header .= $head[$i]."\t";
}
$data = "";
while($row = $result->fetch(PDO::FETCH_ASSOC)/*mysql_fetch_row($rec)*/){
$line = '';
foreach($row as $value){
if((!isset($value)) || ($value == " ")){
$value = "\t";
}else{
$value = str_replace( '"' , '""' , $value );
$value = '"' . $value . '"' . "\t";
}//end of if-else
$line .= $value;
}//end of foreach
$data .= trim( $line ) . "\n";
}//end of while($row = mysql_fetch_row($rec))
$data = str_replace("\r" , "" , $data);
if ($data == ""){
$data = "\n No Record Found!\n";
}
header('Content-Description: File Transfer');
header('Content-Type: application/ms-excel; charset=utf8');
header("Content-Disposition: attachment; filename=Student_data.xls");
//header("Content-Transfer-Encoding: binary ");
header("Expires: 0");
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header("Pragma: public");
print "$header\n$data";
no the data i get from the Mysql qquery is with greek characters
Make sure your database connection is UTF-8 encoded. See UTF-8 all the way through on how to do that.

Is there a PHP script that can convert HTML table data to various formats?

Using PHP, I can convert MySQL data or static table data to csv, Excel, JSON, MySQL etc but is there a useful conversion script or tool that can convert table data into other formatted/styled formats such as PDF and/or JPG/PNG using the PHP GD Library or other?
I've used this before to turn a HTML table into a PDF. I generated the table from a MySQL query.
To export to Excel I use the following code:
<?php
/* Define our Database and Table Info */
$username="";
$password="";
$database="";
$table="";
mysql_connect(localhost,$username,$password);
#mysql_select_db($database) or die( "Unable to select database");
$select = "SELECT * FROM $table";
$export = mysql_query($select);
$fields = mysql_num_fields($export);
for ($i = 0; $i < $fields; $i++) {
$header .= mysql_field_name($export, $i) . "\t";
}
while($row = mysql_fetch_row($export)) {
$line = '';
foreach($row as $value) {
if ((!isset($value)) OR ($value == "")) {
$value = "\t";
} else {
$value = str_replace('"', '""', $value);
$value = '"' . $value . '"' . "\t";
}
$line .= $value;
}
$data .= trim($line)."\n";
}
$data = str_replace("\r","",$data);
if ($data == "") {
$data = "\n(0) Records Found!\n";
}
header("Content-type: application/x-msdownload");
header("Content-Disposition: attachment; filename=mailinglist.xls");
header("Pragma: no-cache");
header("Expires: 0");
print "$header\n$data";
?>
Now be careful with how you include this. It's using the Headers to send the file information to force a download, by doing this you can't have any white space anywhere before these headers are sent otherwise it may throw an error. I usually have this link open as a new window to prevent anything from happening... Again this is just a pretty basic script that can be expanded greatly. Hope this Helps!
<?php
/ Define our Database and Table Info /
$username="";
$password="";
$database="";
$table="";
mysql_connect(localhost,$username,$password);
#mysql_select_db($database) or die( "Unable to select database");
$select = "SELECT * FROM $table";
$export = mysql_query($select);
$fields = mysql_num_fields($export);
for ($i = 0; $i < $fields; $i++) {
$header .= mysql_field_name($export, $i) . ",";
}
while($row = mysql_fetch_row($export)) {
$line = '';
foreach($row as $value) {
if ((!isset($value)) OR ($value == "")) {
$value = ",";
} else {
$value = str_replace('"', '""', $value);
$value = '"' . $value . '"' . ",";
}
$line .= $value;
}
$data .= trim($line)."n";
}
$data = str_replace("r","",$data);
if ($data == "") {
$data = "n(0) Records Found!n";
}
header("Content-type: application/x-msdownload");
header("Content-Disposition: attachment; filename=mailinglist.xls");
header("Pragma: no-cache");
header("Expires: 0");
print "$headern$data";
?>

Categories