Exporting a query to CSV - php

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/

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);

output column names from custom query in mysql

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?

How to make select queries repeatedly with php?

Basically what I need is to make queries that depend on the values ​​of a text file that I'm reading.
This is the code that I have.
$con = mysqli_connect($host,$name,$pass,$db);
$file = fopen($_FILES["file"]["tmp_name"], "r") or die("Unable to open file!");
while(!feof($file))
{
$codigo = fgets($file);
$result = mysqli_query($con,"SELECT column FROM table WHERE column='". $codigo."'");
$row = mysqli_fetch_array($result);
echo $row;
}
fclose($file);
mysqli_close($con);
But I can´t get that I want. I have some values in my text file but when I excecute this I only get the query of the last value of my text file.
Any suggestion?
If I add this line inside the while:
echo $codigo . "<br>";
All the content of my text file are printed, so I think the problem is in the result variable. All the values of the text file return a null value when I make the query except the last.
Try
print_r($row);
or
echo $row["column"];
instead of
echo $row;
Otherwise you will always have "Array" returned.
The solution is someting stupid, when I read a file line by line, PHP also read the newline (\n) so when I make a query the where condition never is true.
A quick solution is make a substring.
What you are doing wrong is this line:
$row = mysqli_fetch_array($result);
And that's why you only see the last result. You keep overwriting that value with the new result. Instead of rewriting the string, keep adding to the array, then after the loop var_dump or print_r the array.
$row[] = mysqli_fetch_array($result);
It also might help you to use mysqli in an object-oriented fashion, the way it was designed:
$result = $con->query($query);

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.

Outputting Query to Textfile

I have this code (which thanks to the users of stackoverflow I got the markup I needed :) ). However, I have come to a road that I have no knowledge of what so ever. I need to output this formatted table of the query to a text file on the server.
<?php
// Make a MySQL Connection
mysql_connect("hostname.net", "user", "pass") or die(mysql_error());
mysql_select_db("database") or die(mysql_error());
// Get all the data from the "example" table
$result = mysql_query("SELECT * FROM cards ORDER BY card_id")
or die(mysql_error());
echo "";
echo " Name AgeTitlebar ";
// keeps getting the next row until there are no more to get
while($row = mysql_fetch_array( $result )) {
// Print out the contents of each row into a table
echo "";
echo $row['card_id'];
echo "";
echo $row['title'];
echo "";
echo $row['item_bar'];
echo "";
}
echo "";
?>
I know I could use something similar to
<?php
$myFile = "test.txt";
$fh = fopen($myFile, 'w') or die("can't open file");
$stringData = "Bobby Bopper\n";
fwrite($fh, $stringData);
fclose($fh);
?>
but I am sure that it cant be the best solution. So I guess my question is does anyone know how to achieve this?
The nicest solution, particularly if you are short on memory, would be to put the writing into the loop:
$fh = fopen('cards.csv', 'w');
// keeps getting the next row until there are no more to get
while($row = mysql_fetch_array( $result )) {
fputcsv($fh, array($row['card_id'], $row['title'], $row['item_bar']), "\t");
}
fclose('cards.csv');
Note that I have used fputcsv to output the data in CSV format (using a tab as the delimiter). This should be easy to read by hand, and will also be easily understood by, for instance, a spreadsheet program. If you preferred a custom format, you should use fwrite as in your question.
Have a look at:
http://dev.mysql.com/doc/refman/5.0/en/select.html
especially:
[INTO OUTFILE 'file_name' export_options
| INTO DUMPFILE 'file_name'
| INTO var_name [, var_name]]
Something like this?
// Make sure the file exists, do some checks.
// Loop trough result set and append anything to the file.
while (false !== ($aRow = mysql_fetch_assoc($rResult))) {
$sCreateString = $aRow['field1'].';'.$aRow['field2'];
file_put_contents('example.txt', $sCreateString, FILE_APPEND);
}
// Done
If you need an exact dump of the database table, there are better options. (much better actually).
If you want to write a text file, then there's nothing wrong with what you've suggested.
There's lots of information in the PHP manual: http://www.php.net/manual/en/ref.filesystem.php
It depends entirely on how you want to store the data inside the file. You can create your own flat-file database format if you wish, and extract the data using PHP once you've read in the file.

Categories