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

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);
}

Related

php script to convert csv to pdf

I'm going to modify the below php script such that it downloads the database as a .pdf file rather than in a .csv format. How should I do that? Currently when this script is called, the database will be downloaded as a .csv file. The database is defined in directadmin.
<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
require 'db.php';
define("tableStuff", "stuff");
define("tableUser", "user");
define("ERR", '{"status":1}');
define("INVALID", '{"status":2}');
define("rowUserId", "user_id");
define("rowRegDate", "reg_date");
define("rowStuffName", "stuff_name");
define("rowPurchaseDate", "purchase_date");
define("rowStuffCount", "stuff_count");
define("rowStuffDescription", "stuff_description");
define("rowPicUrl", "pic_url");
define("rowUserName", "user_name");
//**********************************************************************
$mysqli = mysqli_connect(DBIP, DBUN, DBPW, DBNAME);
if ($mysqli->connect_errno) {
echo ERR;
die;
}
mysqli_set_charset($mysqli, "utf8");
$result = $mysqli->query("SELECT ".rowStuffName.",".rowStuffCount.",".rowStuffDescription.",".rowPurchaseDate.",".tableStuff.".".rowRegDate.",".rowUserName." FROM " . tableStuff .",".tableUser.
" WHERE " . tableStuff.".".rowUserId . " = " . tableUser.".".rowUserId);
if ($result->num_rows > 0) {
$array = array();
while ($row = $result->fetch_array(MYSQL_ASSOC)) {
$array[] = $row;
}
header('Content-Encoding: UTF-8');
header('Content-Type: application/csv; charset=utf-8' );
header(sprintf( 'Content-Disposition: attachment; filename=stuff.csv', date( 'dmY-His' ) ) );
header('Content-Transfer-Encoding: binary');
header('Expires: 0');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Pragma: public');
//echo pack("CCC",0xef,0xbb,0xbf);
$title = array("نام کالا","تعداد (مقدار)","توضیحات","زمان ثبت","نام فرد ثبت کننده");
$out = fopen("php://output", 'w');
//fputs($out,"\xEF\xBB\xBF");
fputcsv($out, $title,"\t");
foreach ($array as $data)
{
fputcsv($out, $data,"\t");
}
fclose($out);
} else {
echo INVALID;
}
mysqli_close($mysqli);
I am late,but i am using FPDF to generate all PDF files,It includes a built in example of making PDF with tables from CSV file,I just changed the source of CSV file.It is super easy.

Export php to csv

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.

Issue with PHP Script with MySQL

My code was working and I don't see issues with it. I tested all the MySQL statements in SQL and everything is fine there.
Everytime it fetches the password variable now it only returns Bad Password as if m_Pass is empty.
Anyone see anything wrong with those statements I don't?
I am using this as a one time password file transfer tool that you have to specify the filename and the password for accessing it.
Then it checks the SQL Database that contains the following format:
id | m_File | m_Pass
0 | Test.txt | testpass
Any help would be appreciated.
Index.php:
<?php
echo <<<EOF
<form method="post" action="Index.php">
File:<input type="text" name="txtFilename"><br>
Password:<input type="text" name="txtPassword">
<input type="submit" value="Download" name="submit">
</form>
EOF;
function doProcess()
{
$servername = "localhost";
$username = "<username>";
$password = "<Password>";
$dbname = "<dbname>";
$filename = $_POST["txtFilename"];
$pass = $_POST["txtPassword"];
echo $filename . "<br>";
if ($filename = ""){
return;
}
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully" . "<br>";
$sql = "SELECT id, m_Pass FROM Main WHERE m_File = '$filename'";
$result = mysqli_query($conn, $sql);
$row = mysqli_fetch_array($result, MYSQLI_ASSOC);
$m_id = $row["id"];
echo $m_id . "<br>";
if ($row["m_Pass"] == $pass){
echo "Downloading.<br>";
//Download File
$filename = utf8_decode("<Path>" . $filename);
if (file_exists($filename)) {
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename='.basename($filename));
header('Content-Transfer-Encoding: binary');
header('Expires: 0');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Pragma: public');
header('Content-Length: ' . filesize($filename));
ob_clean();
flush();
readfile($filename);
$sql = "delete from Main where id = '$m_id'";
$result = mysqli_query($conn, $sql);
}
} else {
echo $pass . " | '" . $row["m_Pass"] . "'<br>";
echo "Bad Password.<br>";
}
echo "Done.<br>";
// Close connection
$conn->close();
}
if(isset($_POST['submit']))
{
doProcess();
}
?>
Got it... Turns out the SQL query command wasnt appending the $filename because of the block:
if ($filename = ""){
return;
}
And I see why... I am assigning the value not comparing lol.

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.

Categories