output column names from custom query in mysql - php

I've created a small input form for a custom sql query using php. I've been able to output the results to a csv form, however I'm having some trouble including the headers in the output file.
I've had no trouble creating an array of the header rows, but I'd like to be able to create the headers out of the query itself.
This is what I've used:
$output = fopen('php://output', 'w');
//get query data
$qs = $_GET['custom'];
$rs = mysqli_query($dbc, $qs)
or die ('Error querying database');
header('Content-Type: text/csv; charset=utf-8');
header('Content-Disposition: attachment; filename=query.csv');
$csv = fopen('php://output', 'w');
while ($row = mysqli_fetch_assoc($rs)) {
fputcsv($csv, $row);
}
fclose($csv);
What I want is a way of inputting the rows from the select before the content of the query (which comes through fine).
I know this will work for set headers if I put it in before the first fputcsv line:
fputcsv($csv, array('col1', 'col2', 'col3', [etc...] ));
but it is only because I define the fields in the array.
What I'm looking for is way to identify the columns in the query and use them as column headers.
I've been attempting to do something with a query that would just get the column names, and then feed that as an array but I can't seem to get it to work. Something like this:
SELECT column_name
FROM information_schema.columns
WHERE table_schema = 'database_name'
and column_name in ($query)
where the $query variable is similar to the $qs query above, but alas no luck. Does anyone know how to do this? Thanks in advance.

fputcsv($csv, array_keys($row)); at the beginning?

Related

How to fetch database result as a stream using PHP/Zend Framework1

I'm writing a CSV file with the results from a function that returns database query results as an array, and getting memory out of exception if the result set is large.
So I'm looking for writing CSV using streams, can anyone help me how to do this using PHP or Zend Framework-1.
You have to change your function to return a statement, not full results. You can use fetch method to get database results per-row and fputcsv to write into a csv file.
$fp = fopen('file.csv', 'w');
$stmt = $db->query('SELECT * FROM table WHERE smth IS NOT NULL ORDER BY id DESC');
while ($row = $stmt->fetch()) {
fputcsv($fp, $fields);
}
fclose($fp);

Extract specific column from a Mysql Table to a CSV file - PDP - MYSQL- PHP

I have written the following code to extract a column from a Mysql Table to a CSV file.
When I ran the script it throws the following error.
Warning: fputcsv() expects parameter 2 to be array, boolean given in
on this line fputcsv($data, $row); Is it problem with the PDO?
header("Content-type: text/csv");
header("Content-Disposition: attachment; filename=".date('m.d.Y').'.csv');
header("Pragma: no-cache");
header("Expires: 0");
define('STOREDIR','upload/csv');
define('ABPATH', dirname(__file__) . '/'); //do not modify this
$stmt = $con->prepare("SELECT fname from abcgroup where group_id='2'");
$stmt->execute();
$stmt->setFetchMode(PDO::FETCH_BOUND);
$stmt->bindColumn('fname', $fname);
$filename = ABPATH.STOREDIR.date('m.d.Y').'.csv';
$data = fopen($filename, 'w');
while ($row = $stmt->fetch()) {
fputcsv($data, $row);
}
fclose($data);
When you use PDO::FETCH_BOUND, $stmt->fetch() returns either true or false, not the row of results. The results are stored in the variables bound with $stmt->bindColumn. So you need to use:
fputcsv($data, array($fname));
But you could just use PDO::FETCH_ASSOC or PDO::FETCH_NUM so that $row will contain the array of columns. Then you can use it in fputcsv() as you have.
Because you're using PDO::FETCH_BOUND, your call to fetch() won't return a data row. It will only return true if success and bind the column content to your variables. From the manual:
PDO::FETCH_BOUND: returns TRUE and assigns the values of the columns in your result set to the PHP variables to which they were bound with the PDOStatement::bindColumn() method
If you want to put the contents of fname in your CSV, use this instead:
fputcsv($data, [$fname]);
Or use a different fetch style to have the row array, such as PDO::FETCH_ASSOC.
$stmt = $con->prepare("SELECT fname from abcgroup where group_id='2'");
Here is the problem
Check the above line ( table name and other details of your table and database like column name and row etc... )

turning db data into csv with header row in php

I have a script that turns a database query result into a csv file. The csv file's first row needs to be the field names of what's defined in the query. Here's what I have so far:
$fp = fopen('report.csv', 'w');
$column_names = array();
foreach($dbh->query($base_query, PDO::FETCH_ASSOC) as $row) {
if (empty($column_names)) {
$column_names = array_keys($row);
fputcsv($fp, $column_names);
}
// additional processing omitted ...
fputcsv($fp, $row);
}
fclose($fp);
Is there a nicer way to populate the column names in the first row of csv (do away with the if condition)? Perhaps do it outside of the loop? or have PDO output the column names before fetching data?
Thanks.
There is always a nicer way, if you separate different operations from each other.
//database part
$data = $dbh->query($base_query)->fetchAll();
// header part
$fp = fopen('report.csv', 'w');
$column_names = array_keys($data[0]);
fputcsv($fp, $column_names);
// body part
foreach($data as $row) {
// additional processing omitted ...
fputcsv($fp, $row);
}
Is there a nicer way to populate the column names in the first row of csv (do away with the if condition)?
No.
Perhaps do it outside of the loop?
Your code is inferring the column names from the keys of the fetched row and as such needs to be inside the loop.
PDO output the column names before fetching data?
This would require an additional query or storing metadata otherwise. Both of which are extra work.

PHP create a complex CSV file

I am in need to create a CSV file getting the data from a mySQL DB.
The fact is that I want the CSV tp be corrected labeled and not just writing the data like this:
id,name,url
1,thisismyname,thisismyurl
I need the CSV file to look well ordered and each data inserted in the relative column.
Also with the function I am going to add below I can only grab the data from the DB and write it to the CSV file as it is. But I need to work with the data and have the CSV labeled in this way:
Campaign Name:
Name of the campaign
Campaign Url:
Url of the campaign
Tot visits:
Tot of visits
Tot unique visits:
Tot of unique visits
id name url
1 thisname this url
2 thisname this url
3 thisname this url
4 thisname this url
5 thisname this url
This is the PHP code I have so far..I need to understand how to achieve a correct structure of the CSV with PHP and adding the lines in it the exact way I want..
Thanks for your help!
function genCSV($filename, $attachment = true, $headers = true) {
// send response headers to the browser
header('Content-Type: text/csv');
header('Content-Disposition: attachment;filename=' . $filename);
$fp = fopen('php://output', 'w');
$query = "SELECT * FROM campaigns";
$result = mysql_query($query) or die(mysql_error());
if ($headers) {
// output header row (if at least one row exists)
$row = mysql_fetch_assoc($result);
if ($row) {
fputcsv($fp, array_keys($row));
// reset pointer back to beginning
mysql_data_seek($result, 0);
}
}
while ($row = mysql_fetch_assoc($result)) {
fputcsv($fp, $row);
}
fclose($fp);
}
Here is a much less elegant solution than the one proposed by #Tom Regner.
I needed to backup certain database tables (all those with a given prefix) but not others. This method, though somewhat slow, allows you to select exactly which tables and which columns from those tables are copied. It was originally written to allow each piece of data to be AES encrypted before being entered into the file but there are other uses for it. As written here, the result is a CSV file with the first line containing the list of columns for the table and the rest containing the data in CSV. It will stand adaptation to output the result of any sql into CSV, if you like.
Obviously: mysqlidb = mysqli databse resource, backups/ = directory to put finished files in.
FWIIW, here is the code:
$sql="SHOW TABLES LIKE 'yourtable%'";
$result = $mysqlidb->query($sql);
$tableresult=$mysqlidb->query($sql);
while($tables=$tableresult->fetch_assoc())
{
$keys=array_keys($tables);
$tablename=$tables[$keys[0]];
echo "Writing $tablename <BR>";
$file=fopen("backups/$tablename.enc","w");
$cols=array();
$sql="SHOW COLUMNS FROM $tablename";
$result=$mysqlidb->query($sql);
while($row=$result->fetch_assoc())
{
$cols[]=$row['Field'];
}
fputcsv($file,$cols);
$sql="SELECT * FROM $tablename";
$result=$mysqlidb->query($sql);
while($row=$result->fetch_assoc())
{
fputcsv($file,$row);
}
fclose($file);
}

Exporting a query to CSV

i need to export the results of this query into a .csv so i can create a chart i just haven't any idea how to go about it and im still semi new to php thanks for any help.
$query="SELECT familyID, Fam_End_Date, Fam_Start_Date,
DATEDIFF(date(Fam_End_Date), date(Fam_Start_Date))
AS Days_Between,
TIMEDIFF(time(Fam_Start_Date), time(Fam_End_Date))
AS Time_Between
FROM family
WHERE Fam_End_Date IS NOT NULL
AND Fam_Start_Date IS NOT NULL
AND year(Fam_Start_Date)='$year'";
$result = mysql_db_query($aidDB, $query, $connection);
Try iterating thru the result set and use fputcsv to write the rows to a file.
http://php.net/manual/en/function.fputcsv.php
For example:
//continuing from your code above:
$fp = fopen('file.csv', 'w');
while ($row = mysql_fetch_assoc($result)) {
fputcsv($fp,$row);
}
fclose($fp);
it is very strait-forward though...
check this:
http://snipplr.com/view/2234/export-mysql-query-results-to-csv/

Categories