Exporting SQLite table to Excel using PHP script - php

I am working on a project and new to PHP and I need to know how to export the table data from SQLite to Excel.
I am able to do it from database but I do not know how to export to Excel using PHP.
<?php
$db = new sqlite3('I:\Preeti\explor\WebMobility.db');
$results = $db->query('SELECT * FROM VerbaliData');
while ($row = $results->fetchArray()) {
var_dump($row);
}
?>

The easiest method whould be to write your results into a CSV file which opens in Excel in a readable format.
See here for more information: http://php.net/fputcsv
$fp = fopen('file.csv', 'w');
while ($row = $results->fetchArray()) {
fputcsv($fp, $row);
}
fclose($fp);

Related

generate pipe delimited file through codeigniter

I am using the below for csv export but i want to export as a pipe delimeted output text file format.
My code generates a txt file using PHP's fputcsv function.
For the delimiter, I am trying to use '|'.
this mycode:
function to_CSV($table) {
$file_csv = "file_csv.csv";
$fp = fopen('php://output', 'w');
$query = "SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA='htmltable' AND TABLE_NAME='$table'";
$result = mysqli_query(db_connect(),$query);
while ($row = mysqli_fetch_row($result)) {
$header[] = $row[0];
}
header('Content-type: application/csv');
header('Content-Disposition: attachment; filename='.$file_csv);
fputcsv($fp, $header);
$query ="SELECT * from $table";
$result = mysqli_query(db_connect(),$query);
while($row = mysqli_fetch_row($result)) {
fputcsv($fp, $row);
}
exit;
}
fclose($fp);
$contents = file_get_contents($file_csv);
$contents = str_replace(",", "|", $contents);
file_put_contents($file_csv, $contents);
How to implementation in codeigniter. help me out please.
thanks a lot.
according to the docs fputcsv format line as CSV and write to file pointer, it has a third parameter which expects a delimiter - take a look at
https://www.php.net/manual/en/function.fputcsv
In your case it means
while($row = mysqli_fetch_row($result)) {
fputcsv($fp, $row, '|');
}
however the main question is - if you use Codeigniter as underlying Framework - why dont you use the model principle and aside of that the provided query builder? - it will make your life much easier.
You can find more informations in their very well written documentation. Take a look at https://codeigniter.com/user_guide/general/models.html?highlight=model

How to create formated Excel lists from mySQL database?

I use a mySQL database and have to create some lists in Excel format (xlsx). The Excel sheets must be formated. For csv export I use phpExcel (I know, it is obsolete but still working).
Which add on do I need to create formated Excel sheets from my mySQL database. I use php to create the frontend.
Thanks,
Markus
This is just a copy of the function i use. It just launches the function when a specific $_GET isset. The function creates a xlsx file. If you want to export the file as .csv you can just change the file extension and edit text/xlsm to text/csv
$gg = $db->prepare("SELECT * FROM beta_mails ORDER BY created DESC");
$gg->execute();
$ggg = $gg->get_result();
$gg->store_result();
while ($row = $ggg->fetch_assoc()) {
$data[] = $row;
}
function getprelaunchCSV(){
global $data;
header('Content-Type: text/xlsx; charset=utf-8');
header('Content-Disposition: attachment; filename=data.xlsx');
// create a file pointer connected to the output stream
$output = fopen('php://output', 'w');
// output the column headings
fputcsv($output, array('ID', 'EMAIL', 'OPRETTET'));
foreach ($data as $rowCSV){
fputcsv($output, [$rowCSV["id"], decrypt($rowCSV["email"]), $rowCSV["created"]]);
}
fclose($output);
die();
}
if (isset($_GET["getlist"]) && $_GET["getlist"] == "1") {
echo getprelaunchcsv();
header("Location:admin?success=1");
}

Export HTML table to CSV file

I am making a script which gets a table from your mail and puts it into a CSV file.
This is the code I use to transfer my html table to CSV
$html = str_get_html($outputstr);
// For Excel
header('Content-type: application/ms-excel');
// Download File
header('Content-Disposition: attachment; filename=sample.csv');
$fp = fopen("php://output", "w");
// Take out empty lines
foreach($html->find('tr') as $element) {
$td = array();
foreach( $element->find('th') as $row) {
$td [] = $row->plaintext;
}
foreach( $element->find('td') as $row) {
$td [] = $row->plaintext;
}
fputcsv($fp, $td);
}
fclose($fp);
The only problem that I'm getting is that when I am opening the CSV file, some of the empty columns have a strange character:
I cannot read through with my PHP script to export it to a database
fgetcsv($handle, 1000, "\t");
How can I fix this problem?
Do I fix this by modifying the code on the part where I create the CSV file or where I read the CSV file when I'm transferring it to a MySQL database?
When I use an online html to CSV converter it works fine and I am not facing this issue then.
If there is any code needed then I'd love to share it.
Any help would be appreciated.
Have you tried setting your charset to UTF-8? Additionally, you're not setting this up as a CSV with your header, instead it is an Excel file.
header("content-type:application/csv;charset=UTF-8");

Generate CSV file on an external FTP server in PHP

I have some PHP code that successfully exports a MySQL table to a CSV file.
I would like to add to that code, so instead of saving locally the CSL file is exported to/saved on an external FTP server.
My current code:
//open database connection
require ('../database-config.php');
//name the file
header('Content-Type: text/csv');
header('Content-Disposition: attachment;filename=exported-data.csv');
//SQL Query for Data
$sql = "SELECT * FROM data;";
//Prepare Query, Bind Parameters, Excute Query
$STH = $dbh->prepare($sql);
$STH->execute();
//Export to .CSV
$fp = fopen('php://output', 'w');
$first_row = $STH->fetch(PDO::FETCH_ASSOC);
$headers = array_keys($first_row);
fputcsv($fp, $headers); // put the headers
fputcsv($fp, array_values($first_row)); // put the first row
while ($row = $STH->fetch(PDO::FETCH_NUM)) {
fputcsv($fp,$row); // push the rest
}
fclose($fp);
I know I'll need to add some new variables;
$ftp_server="ftp.remotersite.com";
$ftp_path="/path/to/somefile";
$ftp_username="username";
$ftp_userpass="password";
But, I'm not sure the best way to use ftp_put (or should it be ftp_fput?) to transfer to the external destination.
Thanks in advance.
If you have ftp:// URL wrappers enabled, just open the file directly on FTP server:
$fp = fopen('ftp://username:password#ftp.example.com/path/to/somefile', 'w');
If you do not have the wrapers enabled, see:
Creating and uploading a file in PHP to an FTP server without saving locally

How can I import data from an XLS file to MySQL?

As I am trying to import MS Excel data to MySQL data base
using the following code:
<?php
$db_username="root"; //database user name
$db_password="";//database password
$db_database="hr_mysql"; //database name
$db_host="localhost";
mysql_connect($db_host,$db_username,$db_password);
#mysql_select_db($db_database) or die( "Unable to connect to database.");
$handle = fopen("UploadIt.xls", "r"); //test.xls excel file name
if ($handle)
{
$array = explode("\n", fread($handle, filesize("UploadIt.xls")));
}
$total_array = count($array);
$i = 0;
$Leave_Type_Id1="LTY001";
$Leave_Type_Id2="LTY002";
while($i < $total_array)
{
$data = explode(",", $array[$i]);
//$sql = "insert into test values ('$data[0]','$data[1]')";
$sql = "update `hs_hr_employee_leave_quota` set `no_of_days_allotted`= {$data[0]} WHERE `employee_id`= {$data[0]} and `leave_type_id`= '{$Leave_Type_Id1}'";
$result = mysql_query($sql);
$sql = "update `hs_hr_employee_leave_quota` set `no_of_days_allotted`= {$data[2]} WHERE `employee_id`= {$data[0]} and `leave_type_id`= '{$Leave_Type_Id2}'";
$result = mysql_query($sql);
$i++;
}
if($result==false)
echo "Not succed";
else
{
echo "completed";
}
?>
And my .xls sheet is:
But I am getting error saying
htdocs\Verify\XL_To_DBTable.php line 28 - Undefined offset: 2
|1|2|5|
|2|3|5|
|3|3|4|
|4|3|9|
|5|4|1|
(Assume above one as xls sheet only)
You need to properly read the file as an MS Excel file. You are treating it as an ascii text file. You could manually dump the file to CSV format and parse it using similar logic to what you have already. Or you could use:
PHP Excel File Reader
and use that to parse the file, get the contents and then create the appropriate queries to be executed in mysql.

Categories