// Database Connection
$host="localhost";
$uname="root";
$pass="";
$database = "xyz";
$connection=mysql_connect($host,$uname,$pass);
echo mysql_error();
//or die("Database Connection Failed");
$selectdb=mysql_select_db($database) or die("Database could not be selected");
$result=mysql_select_db($database)
or die("database cannot be selected <br>");
// Fetch Record from Database
$output = "";
$table = ""; // Enter Your Table Name
$sql = mysql_query("select * from $table");
$columns_total = mysql_num_fields($sql);
// Get The Field Name
for ($i = 0; $i < $columns_total; $i++) {
$heading = mysql_field_name($sql, $i);
$output .= '"'.$heading.'",';
}
$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;
Create a connection and use following code for CSV generation in PHP.
$result = mysqli_query ($mysqliConn,"SELECT * FROM core ORDER BY start_datetime ASC");
$fields = mysqli_fetch_fields($result);
if (!$result) die('Couldn\'t fetch records');
$num_fields = mysqli_fetch_fields($result);
$headers = array();
foreach ($fields as $field) {
$headers[] = $field->name;
}
$fp = fopen('php://output', 'w');
if ($fp && $result) {
header('Content-Type: text/csv');
header('Content-Disposition: attachment; filename="core.csv"');
header('Pragma: no-cache');
header('Expires: 0');
fputcsv($fp, $headers);
while ($row = $result->fetch_array(MYSQLI_NUM)) {
fputcsv($fp, array_values($row));
}
die;
}
Hope this helps.
Related
I am using php to run a SQL Query and populate a HTML Table. My question is, since I have the $query variable house the sql results, would it be possible to add a button to "Export To CSV" and if the button is clicked it will export a .csv file of the $query that is formatted the same way that the html table that is generated?
Say the query string is like this:
$query .= "Select red, green, blue from colorsDB where signoff is not null";
$db->setQuery($query);
$query = $db->loadObjectList();
You can try this way
$result = mysql_query('SELECT * FROM `some_table`');
if (!$result) die('Couldn\'t fetch records');
$num_fields = mysql_num_fields($result);
$headers = array();
for ($i = 0; $i < $num_fields; $i++)
{
$headers[] = mysql_field_name($result , $i);
}
$fp = fopen('php://output', 'w');
if ($fp && $result)
{
header('Content-Type: text/csv');
header('Content-Disposition: attachment; filename="export.csv"');
header('Pragma: no-cache');
header('Expires: 0');
fputcsv($fp, $headers);
while ($row = mysql_fetch_row($result))
{
fputcsv($fp, array_values($row));
}
die;
}
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
While exporting file to csv,my contents are added in the same row of column names.I want content just below to the respective columns.The code is as follow
<?php
$filename = "file.csv";
$fp = fopen('php://output', 'w');
header('Content-type: application/csv');
header('Content-Disposition: attachment; filename='.$filename);
$headerLine = 'Sr. No,Name,DOB,Address';
fwrite($fp, $headerLine);
$query = "select * from registratin";
$result = mssql_query($query);
$i = 1;
while($row = mssql_fetch_row($result)) {
$row = array_merge(array($i), $row);
fputcsv($fp, $row);
$i++;
}
?>
You can do it simply as follows , there is no need to array merge
<?php
$filename = "file.csv";
$fp = fopen('php://output', 'w');
header('Content-type: application/csv');
header('Content-Disposition: attachment; filename='.$filename);
$headerLine = 'Sr. No,Name,DOB,Address';
fputcsv($fp, explode(",",$headerLine); // adding heading
$query = "select * from registratin";
$result = mssql_query($query);
$i = 1;
while($row = mssql_fetch_row($result)) {
//$row = array_merge(array($i), $row); ***no need***
fputcsv($fp, $row);
$i++;
}
fclose($fp);
?>
Its better to use mysqli, and this is the simple way to get the work done.
And in select choose only required columns.
header('Content-Type: text/csv; charset=utf-8');
header('Content-Disposition: attachment; filename=data.csv');
$output = fopen('php://output', 'w');
fputcsv($output, array('SR No', 'Name','DOB','Address'));
$conn = mysqli_connect('localhost', 'root', 'password',"database");
$rows = mysqli_query($conn,'SELECT * from registration');
while ($row = mysqli_fetch_assoc($rows))
fputcsv($output, $row);
I have a script that outputs a SQL query to a CSV file, which works ok but as soon as the content exported contains a ':' only text up until the ':' is displayed.
<?php
include 'connect.php';
date_default_timezone_set('Europe/London');
$date = date('Y-m-d');
//echo $date;
if(isset($_POST['export_query'])){
$querytemp=$_POST['export_query'];
}
//$querytemp = "SELECT * FROM poc_report_live WHERE Date = '$date'";
$result = mysql_query($querytemp);
//if (!$result) die($querytemp);
if (!$result) die('Couldn\'t fetch records');
$num_fields = mysql_num_fields($result);
$headers = array();
for ($i = 0; $i < $num_fields; $i++) {
$headers[] = mysql_field_name($result , $i);
}
$fp = fopen('php://output', 'w');
if ($fp && $result) {
header('Content-Type: text/csv');
header('charset = UTF-8');
header('Content-Disposition: attachment; filename="export.csv"');
header('Pragma: no-cache');
header('Expires: 0');
fputcsv($fp, $headers);
while ($row = mysql_fetch_array($result, MYSQLI_NUM)) {
fputcsv($fp, array_values($row));
}
die;
}
?>
I am really new to php and everything I have learned is from my school textbook and online research. With that said I am trying to complete an assignment and I am stuck on the last part. for the final part the assignment says to "Create a PHP script that will dump the contents of the employee table into CSV text file that has comma separated values for each record. Each new record should begin on a new line". I have tried many online tutorials but none of them teach how to put this event in a button. I am including my code so you can see the mess I have. It's not to bad but I am sure I can do the same task with much less code. Again I am just starting out and this is the best I can do for now. Could anyone give any suggestions on how this could be done. I have my button on line 140. I also used a db_connect() function so i don't have to write it many times. I can peon use this to read the database before I save as a csv.
Any suggestions would be greatly appreciated. Be warned It's a lot of code to follow.
<h2>Employee Search</h2>
<form action="Draft.php" name="dbToCSV" method="GET">
<input type="submit" name="dbToCSV" value="Export Database to CSV" <?php if (isset($_GET['dbToCSV']))
{
//Do this code
}
else
{
echo "Error!";
} ?>><br />
</form>
<form action="Draft.php" method="GET">
By name: <input type="text" name="searchName">
<input type="submit" value="Search Name"><br />
</form>
<form action="Draft.php" method="GET">
By language: <input type="text" name="searchLang">
<input type="submit" value="Search Language"><br />
</form>
It's 2017 and mysqli is more common than mysql now. So here's a mysqli version of Josh Liptzin's answer:
<?php
/* Attempt MySQL server connection. */
$connection = mysqli_connect($database_server, $database_username, $database_password, $database_name);
// Check connection
if($connection === false){
die("ERROR: Could not connect. " . mysqli_connect_error());
}
$query = "SELECT * FROM Employee_data";
$result = mysqli_query($connection, $query);
$number_of_fields = mysqli_num_fields($result);
$headers = array();
for ($i = 0; $i < $number_of_fields; $i++) {
$headers[] = mysqli_field_name($result , $i);
}
$fp = fopen('php://output', 'w');
if ($fp && $result) {
header('Content-Type: text/csv');
header('Content-Disposition: attachment; filename="export.csv"');
header('Pragma: no-cache');
header('Expires: 0');
fputcsv($fp, $headers);
while ($row = $result->fetch_array(MYSQLI_NUM)) {
fputcsv($fp, array_values($row));
}
die;
}
function mysqli_field_name($result, $field_offset)
{
$properties = mysqli_fetch_field_direct($result, $field_offset);
return is_object($properties) ? $properties->name : null;
}
?>
You are literally trying to put the PHP code inside the HTML button. The button can simply be a link to another page (like dump.php), which contains some PHP like the following:
Link:
Download employee data
dump.php:
<?php
$result = mysql_query('SELECT * FROM `employee_data`');
if (!$result) die('Couldn\'t fetch records');
$num_fields = mysql_num_fields($result);
$headers = array();
for ($i = 0; $i < $num_fields; $i++) {
$headers[] = mysql_field_name($result , $i);
}
$fp = fopen('php://output', 'w');
if ($fp && $result) {
header('Content-Type: text/csv');
header('Content-Disposition: attachment; filename="export.csv"');
header('Pragma: no-cache');
header('Expires: 0');
fputcsv($fp, $headers);
while ($row = $result->fetch_array(MYSQLI_NUM)) {
fputcsv($fp, array_values($row));
}
die;
}
?>
Code source: PHP code to convert a MySQL query to CSV
For your own sake you shouldn't copy and paste the above code into your assignment - there's a world of difference between the code you posted and the code above that the grader will instantly pick up on.
So the class is over and I figure I would show how I resolved my issue. this made the most sense to me and it didn't take many lines of code. I am sure there are possibly even shorter ways to do this but for being very new to php i thing I did an ok job with the code.
I basically made an if statement that checks if there are any records in the database then it takes each record field and writes it to the cdv file while adding a comma. I did this code twice. The top code writes the database field names and the second half writes the values in those fields. Thanks for the advice everyone. I am glad I was able to figure it out in time to submit my assignment.
if (isset($_GET['dbToCSV']))
{
// database connection
db_connect();
$query = mysql_query("SELECT * FROM employee_data") or die(mysql_error());
$number_rows = mysql_num_rows($query);
if ($number_rows >= 1)
{
$filename = "exported_db_" . date("m-d-Y_hia") . ".csv"; // filenme with date appended
$fp = fopen($filename, "w"); // open file
$row = mysql_fetch_assoc($query);
$seperator = "";
$comma = "";
foreach ($row as $name => $value)
{
$seperator .= $comma . $name; // write first value without a comma
$comma = ","; // add comma in front of each following value
}
$seperator .= "\n";
echo "Database has been exported to $filename";
fputs($fp, $seperator);
mysql_data_seek($query, 0); // use previous query leaving out first row
while($row = mysql_fetch_assoc($query))
{
$seperator = "";
$comma = "";
foreach ($row as $name => $value)
{
$seperator .= $comma . $value; // write first value without a comma
$comma = ","; // add comma in front of each following value
}
$seperator .= "\n";
fputs($fp, $seperator);
}
fclose($fp);
}
else
echo "There are no records in the database to export.";
mysql_close();
}
Following is PHP script which I am using.
<?php
$link = mysql_connect('localhost', 'mysql_user', 'mysql_password');
if (!$link) {
die('Could not connect: ' . mysql_error());
}
$table_name = "employees";
$fp = fopen('php://output', 'w');
header('Content-Type: text/csv');
header('Content-Disposition: attachment; filename="'.$table_name.'.csv"');
header('Pragma: no-cache');
header('Expires: 0');
$result = mysql_query("SELECT * FROM $table_name");
if (!$result) die("Couldn't fetch records");
$num_fields = mysql_num_fields($result);
$headers = array();
for ($i = 0; $i < $num_fields; $i++) {
$headers[] = mysql_field_name($result , $i);
}
if ($fp && $result) {
fputcsv($fp, $headers);
while ($row = mysql_fetch_assoc($result)) {
fputcsv($fp, $row);
}
}
exit;
?>