Export php to csv - php

I would like to ask if it is possible that before exporting php data to csv it would be query first or filtered(ex: searching a name)? I have a code in exporting php data to csv but I would like it to be filtered first.
This is my code of exporting php data to csv.
<?php
// call export function
exportMysqlToCsv('export_csv.csv');
// export csv
function exportMysqlToCsv($filename = 'export_csv.csv')
{
$conn = dbConnection();
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql_query = "SELECT id, name, code FROM toy";
// Gets the data from the database
$result = $conn->query($sql_query);
$f = fopen('php://temp', 'wt');
$first = true;
while ($row = $result->fetch_assoc()) {
if ($first) {
fputcsv($f, array_keys($row));
$first = false;
}
fputcsv($f, $row);
} // end while
$conn->close();
$size = ftell($f);
rewind($f);
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Content-Length: $size");
// Output to browser with appropriate mime type, you choose ;)
header("Content-type: text/x-csv");
header("Content-type: text/csv");
header("Content-type: application/csv");
header("Content-Disposition: attachment; filename=$filename");
fpassthru($f);
exit;
}
// db connection function
function dbConnection(){
$servername = "localhost";
$username = "root";
$password = "louchin";
$dbname = "phppot_examples";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
return $conn;
}
?>
Please help me and suggest if possible. Thank you!

The data is called up in the SQL query:
$sql_query = "SELECT id, name, code FROM toy";
I think you can just add a WHERE clause to this to add your filters.
A quick Google for 'MySQL WHERE' will give you plenty of places you can look up the syntax.

Related

Issue forcing download of CSV File | PHP

Essentially I have the following script that should interpret the data from the query, format as CSV and download the CSV file.
While the data and CSV structure is being generated correctly, the file is not downloading. Instead the data is just being presented on the web page:
<?php
//Our MySQL connection details.
$host = '';
$user = '';
$password = '';
$database = '';
//Connect to MySQL using PDO.
$pdo = new PDO("mysql:host=$host;dbname=$database", $user, $password);
//Create our SQL query.
$sql = " ";
//Prepare our SQL query.
$statement = $pdo->prepare($sql);
//Executre our SQL query.
$statement->execute();
//Fetch all of the rows from our MySQL table.
$rows = $statement->fetchAll(PDO::FETCH_ASSOC);
//Get the column names.
$columnNames = array();
if(!empty($rows)){
//We only need to loop through the first row of our result
//in order to collate the column names.
$firstRow = $rows[0];
foreach($firstRow as $colName => $val){
$columnNames[] = $colName;
}
}
//Setup the filename that our CSV will have when it is downloaded.
$fileName = 'mysql-export.csv';
//Set the Content-Type and Content-Disposition headers to force the download.
header('Content-Type: application/csv');
header("Content-Disposition: attachment; filename=mysql-export.csv");
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header("Content-Type: application/octet-stream");
header("Content-type: application/force-download");
//Open up a file pointer
$fp = fopen('php://output', 'w');
//Start off by writing the column names to the file.
fputcsv($fp, $columnNames);
//Then, loop through the rows and write them to the CSV file.
foreach ($rows as $row) {
fputcsv($fp, $row);
}
//Close the file pointer.
fclose($fp);
The headers should be:
header('Content-Type: text/csv');
header('Content-Disposition: attachment; filename="mysql-export.csv"');
Note that it's "text/csv", not "application/csv". And you shouldn't need the other two (application/octet-stream and application/force-download). I hope that helps.

Fetching the pdf file from database in php

I am getting an error to fetch the pdf file from the database.Below mentioned is my code,please review my code and give me your valuable suggestion.And it's showing output as failed to open the document.Please help me.
<?php
$server = 'localhost';
$user = 'root';
$pass = '';
$db = 'upload';
// Connect to Database
$connection = mysql_connect($server, $user, $pass) or die ("Could not connect to server ... \n" . mysql_error ());
mysql_select_db($db) or die ("Could not connect to database ... \n" . mysql_error ());
$id = intval($_GET['id']);
$file= 'SELECT `name`,`size`, `created`,`data` FROM `upload`';
$result = mysql_query($file);
if($d = mysql_fetch_array($result))
{
$file = $d['name'];
header('Content-type: application/pdf');
header("Content-Disposition: inline; name=".$row['name']);
header('Content-Transfer-Encoding: binary');
header('Content-Length: ' . size($file));
header('Accept-Ranges: bytes');
header("Location: $file");
#readfile($file);
}
else{
echo'No file with the specified ID exists';
}
?>
One issue that I see is the single "=" in your if statement. '=' is for assignment and '==' is for comparison.
Try changing
if($d = mysql_fetch_array($result))
to
if($d == mysql_fetch_array($result))
EDIT: However, I don't think that will quite work either. I would try
$d = mysql_fetch_array($result);
if ($d === true)
if($result) {
// Make sure the result is valid
if($result->num_rows == 1) {
$row = mysqli_fetch_assoc($result);
header('Content-type: application/pdf');
header("Content-Disposition: inline; name=".$row['name']);
header('Content-Transfer-Encoding: binary');
header("Content-Length: ". $row['size']);
header('Accept-Ranges: bytes');
// Print data
#readfile($row['data']);
echo $row['data'];
}
else {
echo 'Error! No image exists with that ID.';
}

Format column csv from export php-mysqli

The code below exports a .csv file with multiple columns. The column "PRET" is General formatted and it contains the price of products with format xx.xx . I want to turn my values in xx,xx. How can I format the column PRET of type Text or should I replace "." with "," when the file is exported?
<?php
// call export function
exportMysqlToCsv('export_stoc.csv');
// export csv
function exportMysqlToCsv($filename = 'export_stoc.csv')
{
$conn = dbConnection();
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
//v
$sql_query = "SELECT
produse.DENUMIRE,
clase.CLASA,
furnizori.NUME_J,
furnizori.NUME_F,
stoc.CANTITATE,
produse.PRET,
produse.VALUTA,
stare.STARE
FROM clase
JOIN produse ON produse.ID_CLASA = clase.ID
JOIN furnizori ON produse.ID_FURNIZOR = furnizori.ID
JOIN stoc ON stoc.ID_PRODUS = produse.ID
JOIN stare ON stare.ID = stoc.ID_STARE;
//execute this sql and fetch your results as needed
// Gets the data from the database
$result = $conn->query($sql_query);
$f = fopen('php://temp', 'wt');
$first = true;
while ($row = $result->fetch_assoc()) {
if ($first) {
fputcsv($f, array_keys($row), ';')
$first = false;
}
fputcsv($f, $row, ';');
} // end while
$conn->close();
$size = ftell($f);
rewind($f);
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Content-Length: $size");
// Output to browser with appropriate mime type, you choose ;)
header("Content-type: text/x-csv");
header("Content-type: text/csv");
header("Content-type: application/csv");
header("Content-Disposition: attachment; filename=$filename");
fpassthru($f);
exit;
}
// db connection function
function dbConnection(){
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "bd";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
return $conn;
}
?>
Thank you!
There are no "formats" in CSV; CSV is just plain-text separated by some separator.
So...
should I replace "." with "," when the file is exported.
...yes.

change separator "," in ";" from Mysqli in .csv

This code export one file.csv and separated the columns with ","
I have another little problem with this code. Regional settings of my PC are not on the US but on Romanian. This means that with the US separation is done by "," and in Romanian by ";" and Excel takes regional settings of the PC.
What can I do to code to make separation by ";" ?
Thank you!
<?php
// call export function
exportMysqlToCsv('export_csv.csv');
// export csv
function exportMysqlToCsv($filename = 'export_csv.csv')
{
$conn = dbConnection();
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql_query = "SELECT id, firstname, lastname FROM MyGuests";
// Gets the data from the database
$result = $conn->query($sql_query);
$f = fopen('php://temp', 'wt');
$first = true;
while ($row = $result->fetch_assoc()) {
if ($first) {
fputcsv($f, array_keys($row));
$first = false;
}
fputcsv($f, $row);
} // end while
$conn->close();
$size = ftell($f);
rewind($f);
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Content-Length: $size");
// Output to browser with appropriate mime type, you choose ;)
header("Content-type: text/x-csv");
header("Content-type: text/csv");
header("Content-type: application/csv");
header("Content-Disposition: attachment; filename=$filename");
fpassthru($f);
exit;
}
// db connection function
function dbConnection(){
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "myDB";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
return $conn;
}
?>
You have to use like below, you can refer put comma as separator in export to CSV in php for more.
$delimiter = ',';
$enclosure = '"';
$f = fopen('php://temp', 'wt');
$first = true;
while ($row = $result->fetch_assoc()) {
fputcsv($f, $row, $delimiter, $enclosure);
}

How to create a file download that will be remove from the database once downloaded

How can I remove the file from the user if the file was successfully downloaded? I have here a download function but I don't know how to do a one time download.
HTML codes with PHP:
<?php
$result=mysql_query("SELECT * FROM school_management");
while($row=mysql_fetch_array($result))
{
?>
<div class="col-xs-6 col-md-3" style="padding-bottom: 10px;">
<div class="thumbnail">
<img src="images/ebooks/<?php echo $row['PICTURE'];?>" alt="...">
</div>
<p><center>Download</center></p>
</div>
<?php
}
?>
file.php
<?php
include('config.php');
$file=$_GET['file'];
echo $file;
header("Content-disposition: attachment; filename=$file");
header("Content-type: application/pdf");
header('Content-Description: File Transfer');
header('Pragma: public');
header('Expires: 0');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
readfile("$file");
?>
My file.php can only download the file with letters in title but if the file has symbols or numbers in the title, I can't download the file. So I changed all the pdf titles for me to be able to download it. Any suggestions to make my file.php download correctly and if the user downloads the file successfully, the file will be deleted from the user's database.
Database Name: caledte1_ebook
Table Name: school_management
Table Columns: ID_NUMBER, EBOOK_FILENAME, PICTURE
Just make a database call in file.php. You probably also want to validate that the file exists before delivering it.
$filename = mysql_real_escape_string($_GET['file']);
$result = mysql_query("SELECT id_number FROM school_management WHERE ebook_filename = '$filename'");
if(mysql_num_rows($result) == 0) {
// Perform error handling
}
mysql_query("DELETE FROM school_management WHERE ebook_filename = '$filename'");
New PHP / HTML File:
<?php
$dbhost = ""; //Enter db host here
$dbuser = ""; //Enter db user here
$dbpass = ""; //Enter db pass here
$dbname = ""; //Enter db name here
$db = new mysqli($dbhost, $dbuser, $dbpass, $dbname);
/* check connection */
if ($db->connect_errno) {
printf("Connect failed: %s\n", $db->connect_error);
exit();
}
$sql = "SELECT * FROM school_management";
if ($result = $db->query($sql)){
while ($row = $result->fetch_assoc()){ ?>
<div class="col-xs-6 col-md-3" style="padding-bottom: 10px;">
<div class="thumbnail">
<img src="images/ebooks/<?php echo $row['PICTURE'];?>" alt="...">
</div>
<p>
<center>
Download
</center>
</p>
</div>
<? }
$result->free();
} else {
printf("Error: %s\n", $db->error);
}
$db->close();
?>
File.php:
<?php
$dbhost = ""; //Enter db host here
$dbuser = ""; //Enter db user here
$dbpass = ""; //Enter db pass here
$dbname = ""; //Enter db name here
$db = new mysqli($dbhost, $dbuser, $dbpass, $dbname);
/* check connection */
if ($db->connect_errno) {
printf("Connect failed: %s\n", $db->connect_error);
exit();
}
$file = $_GET['file'];
if (file_exists($file)) {
header('Content-Description: File Transfer');
header('Content-Type: application/pdf');
header('Content-Disposition: attachment; filename='.basename($file));
header('Expires: 0');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Pragma: public');
header('Content-Length: ' . filesize($file));
readfile($file);
$file = $db->real_escape_string($file);
$sql = "DELETE FROM school_management WHERE ebook_filename = '". $file ."'";
if ($succes = $db->query($sql)){
//Succesfull deleted code handle here
} else {
printf("Error: %s\n", $db->error);
}
$db->close();
}
?>
Ofcourse you could take the mysqli() connection parts out of these and use a seperate file for that.

Categories