Submit SQL data to CSV file using PHP - php

Hi I am trying to submit msSQL data to create a csv file using PHP; however, when I click submit the csv file is never created. I am wondering if it has something to do with the way I am reading from my database. But I am new to php and sql programming and I am lost as to what is going wrong. Also I have no errors. My code is below.
<p>
<input name="submit" class="submit" type="submit" value="SUBMIT" />
</p>
<?php
if(isset($_POST['submit']))
{
$db = get_db_connection('swcrc');
$db->connect();
$filename = 'uploads/'.strtotime("now").'.csv';
$fp = fopen($filename,"w");
$db->query("SELECT [request_ID], [user_ID], [complete], [comment], [response_date], [animalClass], [animalCommon], [bioSurveyStatus] FROM dbo.Response");
$num_rows = mysql_num_rows($db);
$row = mysql_fetch_assoc($db);
$seperator = "";
$comma = "";
foreach($row as $name => $value)
{
$seperator .= $comma . '' .str_replace('','""',$name);
$comma = ",";
}
$seperator = "\n";
echo $seperator;
fputs($fp,$seperator);
mysql_data_seek($db,0);
while($row = mysql_fetch_assoc($db))
{
$seperator = "";
$comma = "";
foreach($row as $name => $value)
{
$seperator .= $comma . '' .str_replace('','""',$value);
$comma = ",";
}
$seperator = "\n";
fputs($fp,$seperator);
}
fclose($fp);
}
?>
Thank you for the help and looking.

Related

Need Help on Export SQL to CSV through PHP

I have this PHP script which is supposed to take an SQL Query and output it to a CSV file, I know that when I run it i'm getting the right Statement put in but it does not seem to generate a file to my uploads folder.
Could anyone debug this for me?
<?php
function ExportExcel($statement)
{
$filename = "uploads/".strtotime("now").'.csv';
$sql = mysql_query("$statement") or die(mysql_error());
$num_rows = mysql_num_rows($sql);
if($num_rows >= 1)
{
$row = mysql_fetch_assoc($sql);
$fp = fopen($filename, "w");
$seperator = "";
$comma = "";
foreach ($row as $name => $value)
{
$seperator .= $comma . '' .str_replace('', '""', $name);
$comma = ",";
}
$seperator .= "\n";
fputs($fp, $seperator);
mysql_data_seek($sql, 0);
while($row = mysql_fetch_assoc($sql))
{
$seperator = "";
$comma = "";
foreach ($row as $name => $value)
{
$seperator .= $comma . '' .str_replace('', '""', $value);
$comma = ",";
}
$seperator .= "\n";
fputs($fp, $seperator);
}
fclose($fp);
echo "<a href='$filename'>Download</a>";
echo $statement;
}
else
{
echo "error";
}
}
?>
If someone has a similar script that uses mysqli that would be nice
here is a example of a export script I use on my apps using MySqli. This will get you started...
<?php
function ExportExcel($statement){
$output = "";
$sql = mysqli_query($db , $statement);
$columns_total = mysqli_num_fields($sql);
// Get The Field Name
for ($i = 0; $i < $columns_total; $i++) {
$heading = mysqli_fetch_field_direct($sql, $i);
$output .= '"'.$heading->name.'",';
}
$output .="\n";
// Get Records from the table
while ($row = mysqli_fetch_array($sql)) {
for ($i = 0; $i < $columns_total; $i++) {
$output .='"'.$row["$i"].'",';
}
$output .="\n";
}
// Download the file
$filename = "CSV_NAME_GOES_HERE.csv";
header('Content-type: application/csv');
header('Content-Disposition: attachment; filename='.$filename);
echo $output;
exit;
}
?>

Getting multi records from check boxes

First of all before anyone here regrets and set this duplicate I don't know will be or not but I tried to search alot but wasn't able to find my answer I created a table from which there are some checkboxes what I want to do is if someone selects 3 entries then the data will be exported for those 3 entries only this is y query what I have done so far
$id = $_POST['select'];
foreach($id as $key) {
echo $key . ", ";
}
$sql = mysqli_query($con, "SELECT * FROM $table WHERE uid IN ('$key')") or die(mysqli_error($con));
$num_rows = mysqli_num_rows($sql);
I dont know why it's giving me the last record only ? it should have given me 3 records like happens in between query it give us the entries of d between 1 and 3 but what if we select id 1 3 5 it shoulld have given these 3 right so for exporting it to excel i did this code found some help working fine but having issue with my query not successful
if($num_rows >= 1)
{
$row = mysqli_fetch_assoc($sql);
$fp = fopen($filename, "w");
$seperator = "";
$comma = "";
foreach ($row as $name => $value)
{
$seperator .= $comma . '' .str_replace('', '""', $name);
$comma = ",";
}
$seperator .= "\n";
fputs($fp, $seperator);
mysqli_data_seek($sql, 0);
while($row = mysqli_fetch_assoc($sql))
{
$seperator = "";
$comma = "";
foreach ($row as $name => $value)
{
$seperator .= $comma . '' .str_replace('', '""', $value);
$comma = ",";
}
$seperator .= "\n";
fputs($fp, $seperator);
}
fclose($fp);
echo "Your file is ready. You can download it from <a href='$filename'>here!</a>";
}
else
{
echo "There is no record in your Database";
}
$key is only going to be the last value in the foreach. Give the following a go:
$id = $_POST['select'];
$key = "";
foreach($id as $vals) {
$key = $key . $vals . ",";
}
$key = trim($key, ",");
$sql = mysqli_query($con, "SELECT * FROM $table WHERE uid IN ('$key')") or die(mysqli_error($con));

Instead of saving CSV file how to Download the file

I am exporting data from a database using CSV extension and I want to download the results as a CSV file. How can I do that?
This is my code:
public function actionExportexcel() {
$con = mysql_connect("localhost", "root", "") or die();
mysql_select_db("fiducial", $con);
$filename = 'uploads/'.strtotime("now").".csv";
$query = mysql_query("SELECT * FROM
(
SELECT employeecode,name,dob,age,sex,employee_relation,company_id
FROM employeedetails
UNION
SELECT employeecode,father_name,father_dob,father_age,father_gender,father_relation,company_id
FROM employeedetails
WHERE father_name IS NOT NULL AND company_id IS NOT NULL
UNION
SELECT employeecode,mother_name,mother_dob,mother_age,mother_gender,mother_relation,company_id
FROM employeedetails
WHERE mother_name IS NOT NULL AND mother_dob IS NOT NULL
)t WHERE t.company_id = '56' ORDER by t.employeecode ") or die(mysql_error());
$num_rows = mysql_num_rows($query);
if($num_rows >= 1)
{
$rows = mysql_fetch_assoc($query);
$seperator = "";
$comma = "";
foreach ($rows as $name => $value)
{
$seperator .= $comma . '' .str_replace('', '""', $name);
$comma = ",";
}
$seperator .= "\n";
$fp = fopen($filename, "w");
fputs($fp, $seperator);
mysql_data_seek($query, 0);
while($rows = mysql_fetch_assoc($query))
{
$seperator = "";
$comma = "";
foreach ($rows as $name => $value)
{
$seperator .= $comma . '' .str_replace('', '""', $value);
$comma = ",";
}
$seperator .= "\n";
fputs($fp, $seperator);
}
echo "Data successfully exported";
fclose($fp);
} else {
echo "No data is Available";
}
}
How can I download it as a CSV file?
You need to set the HTTP headers correctly for a CSV file download and then instead of writing your query results to a CSV file on the local server, you need to write it to the PHP output buffer (php://output):
Full working example:
public function actionExportexcel() {
$con = mysql_connect("localhost", "root", "") or die();
mysql_select_db("fiducial", $con);
$filename = 'uploads/'.strtotime("now").".csv";
$query = mysql_query("SELECT * FROM
(
SELECT employeecode,name,dob,age,sex,employee_relation,company_id
FROM employeedetails
UNION
SELECT employeecode,father_name,father_dob,father_age,father_gender,father_relation,company_id
FROM employeedetails
WHERE father_name IS NOT NULL AND company_id IS NOT NULL
UNION
SELECT employeecode,mother_name,mother_dob,mother_age,mother_gender,mother_relation,company_id
FROM employeedetails
WHERE mother_name IS NOT NULL AND mother_dob IS NOT NULL
)t WHERE t.company_id = '56' ORDER by t.employeecode ") or die(mysql_error());
$num_rows = mysql_num_rows($query);
if($num_rows >= 1) {
header('Content-Description: Your Download Name ');
header('Content-Type: application/csv');
header('Content-Disposition: attachment; filename=yourfilename.csv');
$rows = mysql_fetch_assoc($query);
$seperator = "";
$comma = "";
foreach ($rows as $name => $value)
{
$seperator .= $comma . '' .str_replace('', '""', $name);
$comma = ",";
}
$seperator .= "\n";
$fp = fopen('php://output', 'w');
fputs($fp, $seperator);
mysql_data_seek($query, 0);
while($rows = mysql_fetch_assoc($query))
{
$seperator = "";
$comma = "";
foreach ($rows as $name => $value)
{
$seperator .= $comma . '' .str_replace('', '""', $value);
$comma = ",";
}
$seperator .= "\n";
fputs($fp, $seperator);
}
fclose($fp);
} else {
echo "No data is Available";
}
}
Use
header('Content-Type: application/excel');
header('Content-Disposition: attachment; filename=<filename>.csv');

excel automatically open file after downloading in php

below is my codes for my excel. its functioning except for one thing. i don't see if my file is already save to excel.. can you help me how to automatically open my file after i download it.. i think something is missing or wrong in my codes.. so please. help . thanks.
{
$conn = mysql_connect("localhost","root","") or die (mysql_error());
mysql_select_db("copylandia",$conn);
//$fp = fopen($filename,"w+");
$filename = 'attachment'. date('Y-m-d') .'.csv';
$fp = fopen($filename,"w+");
$sql = mysql_query("select * from user") or die (mysql_error());
$num_rows = mysql_num_rows($sql);
if($num_rows >= 1)
{
$row = mysql_fetch_assoc($sql);
$fp = fopen($filename,"w+");
$seperator = "";
$comma = "";
foreach($row as $name => $value)
{
$seperator .= $comma .'' . str_replace('','""',$name);
$comma = ",";
}
$seperator .= "\n";
//echo $seperator;
fputs($fp,$seperator);
mysql_data_seek($sql, 0);
while($row = mysql_fetch_assoc($sql))
{
$seperator = "";
$comma = "";
foreach($row as $name => $value)
{
$seperator .= $comma .'' . str_replace('','""',$value);
$comma = ",";
}
$seperator .= "\n";
fputs($fp,$seperator);
}
fclose($fp);
}
else
{
echo 'No records in the database!';
}
}
You can't force the browser/computer to open a file after download. The user must make that decision.
Although, since you are trying to make a CSV file, I will at least make a suggestion to help you out instead of crushing your dreams by telling you you can't do this:
Try fputcsv() instead of trying to make the string yourself:
I'm really cool! Click me!

PHP export to Excel file gives me source code in columns

I feel like I'm making a simple mistake but I can't seem to figure out what.
I have some code for exporting a mySQL table to an Excel file.
However, when I do the export, the entire HTML source code gets exported along with my data. I open the file in Excel and my table data in there but it's also got all the HTML inside.
What could be causing all the source code to be exported along with the data?
I should mention that I'm using this code as part of a Wordpress plugin I'm writing. When I test the export outside wordpress, it works fine. But when I try to export from a Wordpress admin page, I get all the extra HTML source code.
Try this code.
$host = 'localhost';
$user = 'mysqlUser';
$pass = 'myUserPass';
$db = 'myDatabase';
$table = 'products_info';
$file = 'export';
$link = mysql_connect($host, $user, $pass) or die("Can not connect." . mysql_error());
mysql_select_db($db) or die("Can not connect.");
$res = mysql_query("SELECT * FROM $table");
// fetch a row and write the column names out to the file
$row = mysql_fetch_assoc($res);
$line = "";
$comma = "";
foreach($row as $name => $value) {
$line .= $comma . '"' . str_replace('"', '""', $name) . '"';
$comma = ",";
}
$line .= "\n";
fputs($fp, $line);
// remove the result pointer back to the start
mysql_data_seek($res, 0);
// and loop through the actual data
while($row = mysql_fetch_assoc($res)) {
$line = "";
$comma = "";
foreach($row as $value) {
$line .= $comma . '"' . str_replace('"', '""', $value) . '"';
$comma = ",";
}
$line .= "\n";
fputs($fp, $line);
}
fclose($fp);
header('Content-type: application/csv');
header('Content-Disposition: attachment; filename="export.csv"');
readfile('export.csv');
Thanks,
Kanji

Categories