Php mysql Get&Post query to excel - php

I have a page that posts to index page like
index.php?coursecode=COURSECODEHERE
My non-variable query works well. Gives me all table as excel file.
I need to use this query with variables.
<?php
require_once('dbconnect.php');
$setCounter = 0;
$setExcelName = "download_excal_file";
$setSql = "SELECT * FROM courses WHERE coursecode POSTED VARIABLE COURSECODE HERE";
$setRec = mysql_query($setSql);
$setCounter = mysql_num_fields($setRec);
for ($i = 0; $i < $setCounter; $i++) {
$setMainHeader .= mysql_field_name($setRec, $i)."\t";
}
while($rec = mysql_fetch_row($setRec)) {
$rowLine = '';
foreach($rec as $value) {
if(!isset($value) || $value == "") {
$value = "\t";
} else {
//It escape all the special charactor, quotes from the data.
$value = strip_tags(str_replace('"', '""', $value));
$value = '"' . $value . '"' . "\t";
}
$rowLine .= $value;
}
$setData .= trim($rowLine)."\n";
}
$setData = str_replace("\r", "", $setData);
if ($setData == "") {
$setData = "\n no matching records found\n";
}
$setCounter = mysql_num_fields($setRec);
//This Header is used to make data download instead of display the data
header("Content-type: application/octet-stream");
header("Content-Disposition: attachment; filename=".$setExcelName."_Reoprt.xls");
header("Pragma: no-cache");
header("Expires: 0");
//It will print all the Table row as Excel file row with selected column name as header.
echo ucwords($setMainHeader)."\n".$setData."\n";
?>
How can i do that ?

1.- mysql_ is deprecated, switch to PDO or mysqli ASAP
2.- Always sanitize the input, you never know who may call your link and insert stuff (or delete stuff) from your database.
Said that, you can do something like:
$setSql = "SELECT * FROM courses WHERE
coursecode LIKE '".sanitizeThisShit($_GET["coursecode"])."'";

Related

downloading db records in csv but getting blank rows

Guys this my code downloads records from mysql as csv but wheresoever in rows there is any value with a comma , it does not download and i get a blank row instead
what could be this solution for this
here is my code
require_once('config.php');
$u =$_REQUEST['u'];
$cs =$_REQUEST['cs'];
$y =$_REQUEST['y'];
$d =$_REQUEST['d'];
$m =$_REQUEST['m'];
$date = "$y-$m-$d";
$todays = date("d-m-Y");
header('Content-Type: text/csv');
header('Content-Disposition: attachment;filename=Mortgage-'.$u.'-Records-'.$date.'.csv');
//select table to export the data
$select_table=mysql_query("SELECT * FROM records WHERE user ='".$u."' AND status ='".$cs."' AND DATE_FORMAT(posted, '%Y-%m-%d') = '$date' ORDER BY id DESC");
$rows = mysql_fetch_assoc($select_table);
if ($rows)
{
getcsv(array_keys($rows));
}
while($rows)
{
getcsv($rows);
$rows = mysql_fetch_assoc($select_table);
}
// get total number of fields present in the database
function getcsv($no_of_field_names)
{
$separate = '';
// do the action for all field names as field name
foreach ($no_of_field_names as $field_name)
{
if (preg_match('/\\r|\\n|,|"/', $field_name))
{
$field_name = '' . str_replace('', $field_name) . '';
}
echo $separate . $field_name;
//sepearte with the comma
$separate = ',';
}
//make new row and line
echo "\r\n";
}
really appreciate your time and help
Change your first part of the code like this:
require_once('config.php');
$u =$_REQUEST['u'];
$cs =$_REQUEST['cs'];
$y =$_REQUEST['y'];
$d =$_REQUEST['d'];
$m =$_REQUEST['m'];
$date = "$y-$m-$d";
$todays = date("d-m-Y");
header('Content-Type: text/csv');
header('Content-Disposition: attachment;filename=Mortgage-'.$u.'-Records-'.$date.'.csv');
//select table to export the data
$select_table=mysql_query("SELECT * FROM records WHERE user ='".$u."' AND status ='".$cs."' AND DATE_FORMAT(posted, '%Y-%m-%d') = '$date' ORDER BY id DESC");
$i = 0;
while($rows = mysql_fetch_assoc($select_table);)
{
if($i === 0) {
getcsv(array_keys($rows));
}
getcsv($rows);
$i++;
}
And do this change in function getcsv - replace this code:
$field_name = '' . str_replace('', $field_name) . '';
with this:
$field_name = '"' . $field_name . '"';
But instead of using mysql_query try to implement PDO because mysql lib is prune to mysql injection and will is deprecated in new php versions.

A blank line is inserted at the beginning when Creating CSV using PHP MySQL

I am trying to get the contents of the MySQL table to a CSV file. Everything works fine except that a blank row is being inserted before the heading label that I pass through Array.
<?php
error_reporting(0);
ob_start();
session_start();
include 'auto_logout.php';
//echo $_SESSION['fullname'];
if ((!isset($_SESSION['ufullname'])) && (!isset($_SESSION['fullname']))) {
/* Redirect browser */
header("Location: index.php");
/* Make sure that code below does not get executed when we redirect. */
exit();
}
$output = "";
require_once('config/config.php');
require_once("includes/ftp_settings.php");
$table = "Download CSV"; // Enter Your Table Name
if (is_array($new_exist) && (is_array($ftp1))) {
$ressd_new = 'select filename from files where uploaded_by IN ("' . implode('","', $new_exist) . '")';
$resd_new = mysql_query($ressd_new);
while ($kkk_new = mysql_fetch_array($resd_new)) {
$gotit_new = $kkk_new[0];
}
$resultka_new = $ftp1;
$sql = 'SELECT slno, filename, uploaded_by, dateadded, timeadded, size FROM files where uploaded_by IN ("' . implode('","', $new_exist) . '") and filename IN ("' . implode('","', $resultka_new) . '") and size != "0"';
} else {
$sql = "SELECT slno, filename, uploaded_by, dateadded, timeadded, size FROM files where ftp_file = '$ftp_server' and ftp_u_file = '$ftp_user_name' and ftp_p_file = '$ftp_user_pass' and size != '0'";
}
$sql = mysql_query($sql);
$columns_total = mysql_num_fields($sql);
// Get The Field Name
$heading1 = array(
"Sl. No.",
"File Name",
"Uploaded By",
"Date Added",
"Time Added",
"Size"
);
$inc = 0;
for ($i = 0; $i < $columns_total; $i++) {
$heading = $heading1[$inc];
$output .= '"' . $heading . '",';
$inc = $inc + 1;
}
$output .= "\n";
// Get Records from the table
while ($row = mysql_fetch_array($sql)) {
for ($i = 0; $i < $columns_total; $i++) {
$output .= '"' . $row["$i"] . '",';
}
$output .= "\n";
}
// Download the file
$filename = "myFile.csv";
header('Content-type: application/csv');
header('Content-Disposition: attachment; filename=' . $filename);
echo $output;
exit;
?>
Not really sure where is the blank line coming from.
Including files will often add unwanted whitespaces if not cared properly.
Suppressing errors will make the things worse in every case.
The reason you need ob_start() is because the script between ob_start() and "echo $output;" is printing some content (your empty line probably). And therfore you can't set headers. I'll bet it's in your included files (auto_logout, config, ftp_settings).
Allow errors, remove ob_start, solve all warnings, profit.
And btw: Do not use mysql extension, use mysqli instead.

How to set up comma delimiter to export each cell from php to csv

I have a php script that exports a data from mysql into the csv. Everything worked fine, when the script was smaller but now, when it reaches a numerous code lines it doesn't do the job.
PROBLEM: it export csv file regularly, but all the tables results are in the first cell of excel. It is supposed to fill each cell - it should recognize in database where there is a comma, then use delimiter and split into cells separately.
So, the delimiter is not working and I don't know why. It should use commas and split it, and it should use | to split again.
This is the code:
$link = mysql_connect($host, $user, $pass) or die("Can not connect." . mysql_error());
mysql_select_db($db) or die("Can not connect.");
$result = mysql_query("SHOW COLUMNS FROM ".$table."");
$columnName = array();
if (mysql_num_rows($result) > 0)
{
while ($row = mysql_fetch_assoc($result))
{
$columnName[] = $row['Field'];
$i++;
}
}
$columnName[] .= "\n";
$needle = '|';
$values = mysql_query("SELECT * FROM ".$table." where id=".$id."");
while ($rowr = mysql_fetch_row($values))
{
for ($j=0;$j<$i;$j++)
{
$colName = $columnName[$j];
$count = strlen($rowr[$j]) - strlen(str_replace(str_split($needle), '', $rowr[$j]));
if ($count > 1)
{
for($p=0;$p<$count;$p++)
{
$colName .= ",";
}
$columnName[$j] = $colName;
$csv_output_column_names .= $columnName[$j].", ";
$csv_output_column_values .= str_replace('|',',',$rowr[$j]).", ";
}
else
{
$csv_output_column_names .= $columnName[$j].", ";
$csv_output_column_values .= $rowr[$j] .", ";
}
}
$csv_output_column_values .= "\n";
}
$csv_output = $csv_output_column_names."\n".$csv_output_column_values;
$filename = $file."_".date("Y-m-d");
header("Content-type: application/vnd.ms-excel");
header("Content-disposition: csv" . date("Y-m-d") . ".csv");
header("Content-disposition: filename=".$filename.".csv");
print $csv_output;
exit;
?>
Your issue is that you're not quoting fields as Excel expects it.
Instead of reinventing the wheel, you should use the already existing fgetcsv and fputcsv functions.
Normally these are used to write to files, but you can create a file handle to standard out so that they're printed to screen. For example:
header("Content-type: application/vnd.ms-excel");
header("Content-disposition: csv" . date("Y-m-d") . ".csv");
header("Content-disposition: filename=".$filename.".csv");
// $lines is a 2D array with all rows and their column data
// $columns is a 1D array with each row's columns (see examples from fputcsv documentation)
$out = fopen("php://stdout", "w");
foreach ($lines as $columns) { fputcsv($out, $columns); }
fclose($out);
You need to care about memory to begin with, including this solves the problem delimited CSV.
Example:
$file = new SplFileObject('php://output', 'w');
$file->fputcsv($rowr, ';', '"');

Export data from MySQL to Excel with UTF-8 encoding

I have a mysql row with utf8_general_ci collation, when I export it to csv, instead of correct utf-8 characters I get Ć…ā€¦I etc, how to make excel understand UTF-8 encoding here is my code:
$conn = mysql_connect('localhost', 'root', 'asdfggh') or die(mysql_error());
mysql_query("SET CHARACTER SET utf8");
mysql_query("SET NAMES utf8");
mysql_select_db('table_name', $conn) or die(mysql_error($conn));
$query = sprintf('SELECT * FROM sudraba_birzs');
$result = mysql_query($query, $conn) or die(mysql_error($conn));
header('Content-Encoding: UTF-8');
header('Content-type: text/csv; charset=UTF-8');
header('Content-Disposition: attachment; filename="'.date("d-m-Y_H:i") . '.csv'.'"');
echo "\xef\xbb\xbf";
$row = mysql_fetch_assoc($result);
if ($row) {
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";
}
How to export it to get all characters display correctly (make Excel understand utf-8) and to maintain table layout too(with rows and columns)
You are generating CSV, which is basically a plain text file. There's no way to specify encoding information in such kind of files. Most text editors implement (better or worse) encoding auto-detection. Excel doesn't. Excel will simply assume ANSI when you right-click on a CSV file. (You need to use the "Open" menu in order to be prompted about encoding.)
Your only option left (apart from switching to another output format) is converting data to ANSI, either with mb_convert_encoding() or with iconv(). But now you have another problem: ANSI is not a real encoding, it basically means "whatever encoding is set in my Windows computer". You first have to find out the typical encoding most of your users have. That mostly depends on the country. For instance, many Western Europe countries use Win-1252.
I had the same problem (common problem in databases with spanish language). I wrote this and it worked:
This is a Class that connects with the database and the functions will do whatever you want using mysqli and PHP. In this case, calling this class (require or include), just use the "downloadCsv()" function.
As an example, this would be the "class.php" file:
<?php
class DB{
private $con;
//this constructor connects with the database
public function __construct(){
$this->con = new mysqli("Your_Host","Your_User","Your_Pass","Your_DatabaseName");
if($this->con->connect_errno > 0){
die('There was a problem [' . $con->connect_error . ']');
}
}
//create the function that will download a csv file from a mysqli query
public function downloadCsv(){
$count = 0;
$header = "";
$data = "";
//query
$result = $this->con->query("SELECT * FROM Your_TableName");
//count fields
$count = $result->field_count;
//columns names
$names = $result->fetch_fields();
//put column names into header
foreach($names as $value) {
$header .= $value->name.";";
}
}
//put rows from your query
while($row = $result->fetch_row()) {
$line = '';
foreach($row as $value) {
if(!isset($value) || $value == "") {
$value = ";"; //in this case, ";" separates columns
} else {
$value = str_replace('"', '""', $value);
$value = '"' . $value . '"' . ";"; //if you change the separator before, change this ";" too
}
$line .= $value;
} //end foreach
$data .= trim($line)."\n";
} //end while
//avoiding problems with data that includes "\r"
$data = str_replace("\r", "", $data);
//if empty query
if ($data == "") {
$data = "\nno matching records found\n";
}
$count = $result->field_count;
//Download csv file
header("Content-type: application/octet-stream");
header("Content-Disposition: attachment; filename=FILENAME.csv");
header("Pragma: no-cache");
header("Expires: 0");
echo $header."\n".$data."\n";
}
?>
After creating the "class.php" file, in this example, use that function on "download.php" file:
<?php
//call the "class.php" file
require_once 'class.php';
//instantiate DB class
$export = new DB();
//call function
$export->downloadCsv();
?>
After download, open the file with MS Excel.
I hope this help you, I think I wrote it well, I didn't feel comfortable with the text and code field.
As an alternate and much sipmler solution, you can try this, i am using it for a few years by now, and never had a problem with it.
db_connect.php
<?php
$mysqli = new mysqli($mysqli_host, $mysqli_user, $mysqli_pass, $mysqli_db);
if ($mysqli->connect_errno)
{
$debug = $debug.'<br/>Failed to connect to MySQL: (' . $mysqli->connect_errno . ') ' . $mysqli->connect_error;
}
else
{
$debug = $debug.'<br/>Connected to '. $mysqli->host_info;
}
?>
Export function
function export($query_exp,$name)
{
require '../lib/db_config.php';
require '../lib/db_connect.php';
$filename = $name.' - '.date('Y.m.d').'.xls'; /*set desired output file name here*/
function cleanData(&$str)
{
$str = preg_replace("/\t/", "\\t", $str);
$str = preg_replace("/\r?\n/", "\\n", $str);
if(strstr($str, '"')) $str = '"' . str_replace('"', '""', $str) . '"';
if ($str=='') {$str='-';}
}
header("Content-Disposition: attachment; filename=\"$filename\"");
header("Content-Type: application/vnd.ms-excel");
$flag = false;
if ($result = $mysqli->query($query_exp))
{
if ($result->num_rows>0)
{
$result->data_seek(0);
while ($row = $result->fetch_assoc())
{
if(!$flag)
{
print implode("\t", array_keys($row)) . "\r\n";
$flag = true;
}
array_walk($row, 'cleanData');
print implode("\t", array_values($row)) . "\r\n";
}
}
else { $debug = $debug.'<br/>Empty result'; /*DEBUG*/ }
}
else { $debug = $debug.'<br/>Oups, Query error!<br/>Query: '.$query_exp.'<br/>Error: '.$mysqli->error.'.'; /*DEBUG*/ }
require '../lib/db_disconnect.php';
}
You can call the function as:
export('SELECT * FROM SAMPLE WHERE 1;','desired_file_name.extension')

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