I have this code that export Database table as csv and I have it like this
ط¨ط§ط±ط§ط³ it should look like this علي. I do not know what is the problem.is it because of encoding or what. and my table Collation is utf8_general_ci
$mysqli = new mysqli('localhost', 'root', '', 'test');
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;
}
function export($query_exp,$name)
{
require 'classs.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 'classs.php';
}
export('SELECT * FROM exel;','file');
After connecting, you need to tell mysql you are sending, and want to receive utf8:
$mysql->query("set names 'utf-8'");
Related
So I have one tiny problem with a script I've been writing to run anytime an admin clicks the backup button.
The functionality is to backup every table in a database, and save them as individual .sql files.
I have been able to create the directory to put them in and even the .sql files themselves, but I can't seem to get it to write to the file.
I would even settle for a one file dump of the entire database, I just need to save it somehow, either to the server or download it to the local machine.
Here is my code.
if(isset($_GET['perform_backup'])) {
$site_connection = mysqli_connect("$db_host", "$db_user_dec", "$db_password_dec", "$db_name_dec") or die("Error Connecting: $DB_ERROR | " . mysqli_error($site_connection));
$web_output .= 'Connected... ' . mysqli_get_host_info($site_connection) . "\n";
if(!$site_connection) {
$web_output .= "Error 12: Unable to connect to MySQL." . PHP_EOL;
$web_output .= "Debugging errno: " . mysqli_connect_errno() . PHP_EOL;
$web_output .= "Debugging error: " . mysqli_connect_error() . PHP_EOL;
} else {
$tableList = array();
$SHOW_TABLES=$site_connection->query("SHOW TABLES FROM $set_db_name") or die("Error 12: " . mysqli_error($site_connection));
$SHOW_TABLES_total = $SHOW_TABLES->num_rows;
if($SHOW_TABLES_total != 0) {
while($row2=mysqli_fetch_assoc($SHOW_TABLES)) {
//$table = $row2[0];
//$web_output .= "[$table] <br />";
$directory_ctr = 0;
$dir_name_backup_new = "site_files/$set_directory_name/backups/$current_date_stamp";
if(is_dir($dir_name_backup_new)) {
$web_output .= "'$dir_name_backup_new' exists.";
$web_output .= "<br />";
} else {
$web_output .= "'$dir_name_backup_new' directory does not exist. <br />";
$web_output .= "Attempting To Create Directroy ... <br />";
mkdir("$dir_name_backup_new");
if(is_dir($dir_name_backup_new)) {
$web_output .= "Success Making Directory!";
} else {
$web_output .= "Failed To Make Directory!";
$directory_ctr++;
}
$web_output .= "<br />";
}
if($directory_ctr == 0) {
foreach($row2 as $key=>$table_name) {
$web_output .= "[$table_name] - ";
$backup_file = "$dir_name_backup_new/$current_date_stamp-$table_name.sql";
$web_output .= "$backup_file <br />";
fopen("$backup_file", "w+");
//$db_stmt = $site_connection->query("SELECT * FROM $table_name");
$db_stmt = $site_connection->query("SELECT * INTO OUTFILE '$backup_file' FROM $table_name");
if(!$db_stmt) {
$web_output .= "Could not take data backup... Error: ".$site_connection->error;
} else {
$web_output .= "Backed-up data successfully.";
}
$web_output .= "<br />";
}
} else {
$web_output .= "Error: Directories Not Created. <br />";
}
}
}
}
echo $web_output;
}
try this
$result = $db_con->query('SELECT * FROM `some_table`');
$fp = fopen('php://output', 'w');
if ($fp && $result) {
header('Content-Type: text/csv');
header('Content-Disposition: attachment; filename="export.csv"');
while ($row = $result->fetch_array(MYSQLI_NUM)) {
fputcsv($fp, array_values($row));
}
die;
}
Try this out.
$para = array(
'db_host'=> '$DB_HOST', //mysql host
'db_uname' => '$DB_USER', //user
'db_password' => '$DB_PASS', //pass
'db_to_backup' => '$DB_NAME', //database name
'db_backup_path' => './sql-backups/', //where to backup
'db_exclude_tables' => array('') //tables to exclude
);
$dbBackup = new backupDB();
$dbBackup->__backup_mysql_database($para);
class backupDB {
private $params;
function __backup_mysql_database($params) {
date_default_timezone_set("America/New_York");
$tables_array = array();
$contents = "-- Database: `".$params['db_to_backup']."` --\n";
$mysqli = new mysqli($params['db_host'], $params['db_uname'], $params['db_password'], $params['db_to_backup']);
if (!$mysqli) {
echo "Error: Unable to connect to MySQL." . PHP_EOL;
echo "Debugging errno: " . mysqli_connect_errno() . PHP_EOL;
echo "Debugging error: " . mysqli_connect_error() . PHP_EOL;
exit;
}
//if ($mysqli->connect_error) {
// die('Error : ('. $mysqli->connect_errno .') '. $mysqli->connect_error);
//}
$show_tables = $mysqli->query("SHOW TABLES");
while($row = $show_tables->fetch_array()){
if (!in_array($row[0], $params['db_exclude_tables'])){
$tables_array[] = $row[0];
}
}
foreach($tables_array as $table){
$contents .= "-- Table `".$table."` --\n";
$show_tables = $mysqli->query("SHOW CREATE TABLE ".$table);
while($row = $show_tables->fetch_array()){
$contents .= $row[1].";\n\n";
}
$show_tables = $mysqli->query("SELECT * FROM ".$table);
$row_count = $show_tables->num_rows;
$fields = $show_tables->fetch_fields();
$fields_count = count($fields);
$insert_head = "INSERT INTO `".$table."` (";
for($i=0; $i < $fields_count; $i++){
$insert_head .= "`".$fields[$i]->name."`";
if($i < $fields_count-1){
$insert_head .= ', ';
}
}
$insert_head .= ")";
$insert_head .= " VALUES\n";
if($row_count>0){
$row_counter = 0;
while($row = $show_tables->fetch_array()){
if(($row_counter % 400) == 0){
$contents .= $insert_head;
}
$contents .= "(";
for($i=0; $i < $fields_count; $i++){
$row_content = str_replace("\n","\\n",$mysqli->real_escape_string($row[$i]));
switch($fields[$i]->type){
case 8: case 3:
$contents .= $row_content;
break;
default:
$contents .= "'". $row_content ."'";
}
if($i < $fields_count-1){
$contents .= ', ';
}
}
if(($row_counter+1) == $row_count || ($row_counter % 400) == 399){
$contents .= ");\n\n";
} else {
$contents .= "),\n";
}
$row_counter++;
}
}
}
if (!is_dir ( $params['db_backup_path'] )) { mkdir ( $params['db_backup_path'], 0777, true ); }
$backup_file_name = $params['db_backup_path']."sql-backup-".date("Y-m-d_H-i-s").".sql";
$fp = fopen($backup_file_name ,'w+');
if (($result = fwrite($fp, $contents))) {
echo "-- Backup file created on ".date("h:i:s a M j, Y")."\n";
}
fclose($fp);
if (file_exists($backup_file_name)) {
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="'.basename($backup_file_name).'"');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize($backup_file_name));
readfile($backup_file_name);
exit;
}
mysqli_close($mysqli);
}
}
Alright, so here is the result I came up with. After using the direction of help from #Pankaj Kaityar's response. I was able to do some more research find a snippet of code that let me make up a function to download a copy of my databases, or save it to the server by the press of one or the other button.
The code is simplified as much as I could, and I'm sure there are other people who could improve this. But this works for me. Anyone else feel free to use it.
//HTML Buttons
Perform Server Backup
Perform Download Backup
//PHP Code
$db_array = array();
$directory_ctr = 0;
$dir_name_backup_new = "site_files/backups/";
if(isset($_GET['perform_new_backup'])) {
include('function_db_export.php');
$site_connection = mysqli_connect("$db_host", "$db_user_dec", "$db_password_dec", "$db_name_dec") or die("Error Connecting: $DB_ERROR | " . mysqli_error($site_connection));
echo 'Connected... ' . mysqli_get_host_info($site_connection) . "<br />";
if(!$site_connection) {
echo "Error 12: Unable to connect to MySQL." . PHP_EOL;
echo "Debugging errno: " . mysqli_connect_errno() . PHP_EOL;
echo "Debugging error: " . mysqli_connect_error() . PHP_EOL;
} else {
$SHOW_TABLES=$site_connection->query("SHOW TABLES FROM $db_name_dec") or die("Error 13: " . mysqli_error($site_connection));
$SHOW_TABLES_total = $SHOW_TABLES->num_rows;
if($SHOW_TABLES_total != 0) {
while($row2=mysqli_fetch_assoc($SHOW_TABLES)) {
if(!is_dir($dir_name_backup_new)) {
echo "'$dir_name_backup_new' directory does not exist. <br />";
echo "Attempting To Create Directroy ... <br />";
mkdir("$dir_name_backup_new");
if(is_dir($dir_name_backup_new)) {
echo "Success Making Directory! <br />";
} else {
echo "Failed To Make Directory! <br />";
$directory_ctr++;
}
}
if($directory_ctr == 0) {
foreach($row2 as $key=>$table_name) {
array_push($db_array,"$table_name");
echo "Found '<u>$table_name</u>' Table... Attempting Backup... <br />";
}
} else {
echo "Error: Directories Not Created. <br />";
}
}//END WHILE
//echo print_r($db_array); //Testing Purposes
$new_file_name = $db_name_dec.'-db-backup-'.$current_date_stamp.'.sql';
if($_GET['perform_new_backup'] == "server") {
$save_setting = $save_location=false;
} elseif($_GET['perform_new_backup'] == "download") {
$save_setting = $dir_name_backup_new;
} else {
$save_setting = $dir_name_backup_new;
}
$cur_page = "$select_variable?id=$website_id";
Export_Database($db_host, $db_user_dec, $db_password_dec, $db_name_dec, $save_setting, $table_name = $db_array, $new_file_name, $cur_page);
} //END IF
}
}
//FUNCTION FILE (function_db_export.php)
function Export_Database($host,$user,$pass,$name,$save_location=false, $tables=false, $backup_name=false, $current_page ) {
global $web_output;
$new_conn = new mysqli($host,$user,$pass,$name);
$new_conn->select_db($name);
$new_conn->query("SET NAMES 'utf8'");
$queryTables = $new_conn->query('SHOW TABLES');
while($row = $queryTables->fetch_row()) {
$target_tables[] = $row[0];
}
if($tables !== false) { $target_tables = array_intersect( $target_tables, $tables); }
foreach($target_tables as $table) {
$result = $new_conn->query('SELECT * FROM '.$table);
$fields_amount = $result->field_count;
$rows_num=$new_conn->affected_rows;
$res = $new_conn->query('SHOW CREATE TABLE '.$table);
$TableMLine = $res->fetch_row();
$content = (!isset($content) ? '' : $content) . "\n\n".$TableMLine[1].";\n\n";
for ($i = 0, $st_counter = 0; $i < $fields_amount; $i++, $st_counter=0) {
while($row = $result->fetch_row()) { //when started (and every after 100 command cycle):
if ($st_counter%100 == 0 || $st_counter == 0 ) {
$content .= "\nINSERT INTO ".$table." VALUES";
}
$content .= "\n(";
for($j=0; $j<$fields_amount; $j++) {
$row[$j] = str_replace("\n","\\n", addslashes($row[$j]) );
if (isset($row[$j])) {
$content .= '"'.$row[$j].'"' ;
} else {
$content .= '""';
}
if ($j<($fields_amount-1)) {
$content.= ',';
}
}
$content .=")";
//every after 100 command cycle [or at last line] ....p.s. but should be inserted 1 cycle earlier
if ( (($st_counter+1)%100==0 && $st_counter!=0) || $st_counter+1==$rows_num) {
$content .= ";";
} else {
$content .= ",";
}
$st_counter=$st_counter+1;
}
} $content .="\n\n\n";
}
if($save_location !== false) {
$myfile = fopen($save_location.$backup_name, "w") or die("Unable to open file!");
fwrite($myfile, $content);
fclose($myfile);
$web_output .= "... Backup Has Completed. <br />";
$web_output .= "Page will refresh in 5 seconds.";
header( "refresh:5;url=$current_page" );
} else {
header('Content-Type: application/octet-stream');
header("Content-Transfer-Encoding: Binary");
header("Content-disposition: attachment; filename=\"".$backup_name."\"");
echo $content; exit();
header( "refresh:5;url=$current_page" );
}
}
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
I create excel file using php.It has contain Query Result data from database.Excel file generate and download very well but when i opened i found it gives some format error and some coding error also.
function generate_excel($conn) {
$filename = "website_data_" . date('Ymd') . ".xls";
function cleanData(&$str) {
$str = preg_replace("/\t/", "\\t", $str);
$str = preg_replace("/\r?\n/", "\\n", $str);
if (strstr($str, '"'))
$str = '"' . str_replace('"', '""', $str) . '"';
}
header("Content-Disposition: attachment; filename=\"$filename\"");
header("Content-type: application/octet-stream;charset=utf-8");
$flag = false;
$qry = "SELECT ContactId,UniqueContactId FROM Contacts ORDER BY ContactId ";
$stmt = sqlsrv_query($conn, $qry);
$row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC);
while (false !== ($row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC))) {
if (!$flag) {
// display field/column names as first row
echo implode("\t", array_keys($row)) . "\r\n";
$flag = true;
}
array_walk($row, 'cleanData');
echo implode("\t", array_values($row)) . "\r\n";
}
exit;
}
sqlsrv_fetch_array() can return either NULL or FALSE. You can make your while statement as follows:
while (NULL !== ($row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC))) {
if(!$row)
break ;
//...
}
Here's PHP function reference: http://php.net/manual/en/function.sqlsrv-fetch-array.php
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')
im working on a php-based system. one of its features is allows user to download an excel file containing all the information in one of my table in my database. my problem is, one data of that information is classified to other users. thus, i want to convert the output of that data into a string of asterisk.
<?PHP
//MySQL Database Connect
include 'datalogin.php';
function cleanData(&$str)
{
$str = preg_replace("/\t/", "\\t", $str);
$str = preg_replace("/\r?\n/", "\\n", $str);
if(strstr($str, '"')) $str = '"' . str_replace('"', '""', $str) . '"';
}
# filename for download
$filename = "website_data_" . date('Ymd') . ".xls";
header("Content-Disposition: attachment; filename=\"$filename\"");
header("Content-Type: application/vnd.ms-excel");
$flag = false;
//$result = pg_query("SELECT * FROM data_mapping ORDER BY CE_Hostname") or die('Query failed!');
/*$query = "SELECT * FROM data_mapping";
while(false !== ($row = pg_fetch_assoc($result))) {
//while(false !== ($row = pg_fetch_assoc($result))) {
//$result=mysql_query($query);
$row=mysql_fetch_array($result);
$row=mysql_fetch_assoc ($result);
//$row=$row['Cust_Segment'];
// foreach($data as $row)
# display field/column names as first row
if(!$flag) {
echo implode("\t", array_keys($row)) . "\r\n";
$flag = true;
}
array_walk($row, 'cleanData');
echo implode("\t",($row)) . "\r\n";
}
*/
$sql = 'SELECT CE_Hostname, Cust_Segment, Cust_Site_Name, CE_WAN_IP_Addr, CE_Bkp_IP_Addr, Cust_Name, Svc_Type, com_string FROM data_mapping';
$result = mysql_query($sql);
if (!$result) {
echo "DB Error, could not query the database<br>";
echo 'MySQL Error: ' . mysql_error();
exit;
}
echo "Hostname\t Group/System\t Site Name\t IP ADDR\t BKP IP ADDR\t System Name\t Device Type\t Comm_String\r\n";
while ($row = mysql_fetch_assoc($result)) {
echo implode("\t",($row)) . "\r\n";
}
mysql_free_result($result);
//exit;
?>
i want to convert only the comm_string result. thanks.
$sql = 'SELECT CE_Hostname, Cust_Segment, Cust_Site_Name, CE_WAN_IP_Addr, CE_Bkp_IP_Addr, Cust_Name, Svc_Type, com_string FROM data_mapping';
Can simply be updated to not included the classified field
$sql = 'SELECT CE_Hostname, Cust_Segment, Cust_Site_Name, CE_WAN_IP_Addr, CE_Bkp_IP_Addr, Cust_Name, Svc_Type FROM data_mapping';
Or if you still want to show some value there without any change in your PHP code then you could do
$sql = 'SELECT CE_Hostname, Cust_Segment, Cust_Site_Name, CE_WAN_IP_Addr, CE_Bkp_IP_Addr, Cust_Name, Svc_Type, 'SECRET' FROM data_mapping';
This will then show SECRET instead of that code
Try this:
while ($row = mysql_fetch_assoc($result))
{
$row['Comm_String'] = preg_replace( '/./', '*', $row['Comm_String'] );
echo implode("\t",($row)) . "\r\n";
}