I have a mysql statement and I would like to store the data it fetches in a csv file in tab format. I have used the following statment but it is not creating and storing the results when I run my file and no error files.
$mytry = "SELECT * FROM table WHERE `assigned` = '$id'
INTO OUTFILE '/inactive/orders.csv'
FIELDS TERMINATED BY ','
ENCLOSED BY '\"'
LINES TERMINATED BY '\n'";
mysql_query($mytry);
Or there a way I can write to file in a directory without prompting the user to download, this works but it prompts
$sQuery="SELECT * FROM table WHERE `assigned` = '$id'";
$rResult = mysql_query( $sQuery) or die();
$count = mysql_num_fields($rResult);
$html = '<table border="1"><thead><tr>%s</tr><thead><tbody>%s</tbody></table>';
$thead = '';
$tbody = '';
$line = '<tr>%s</tr>';
for ($i = 0; $i < $count; $i++){
$thead .= sprintf('<th>%s</th>',mysql_field_name($rResult, $i));
}
while(false !== ($row = mysql_fetch_row($rResult))){
$trow = '';
foreach($row as $value){
$trow .= sprintf('<td>%s</td>', $value);
}
$tbody .= sprintf($line, $trow);
}
header("Content-type: application/vnd.ms-excel; name='excel'");
header("Content-Disposition: filename=exportfile.xls");
header("Pragma: no-cache");
header("Expires: 0");
print sprintf($html, $thead, $tbody);
exit;
You might want to look into the following PHP function: http://php.net/manual/en/function.fputcsv.php
Fetch the data using your query and then save it to a variable. Then, use fputcsv
to store the data to a file.
Also, I would discourage the usage of mysql_query
, since it has now become deprecated (as well as the rest of mysql_*
family). Furthermore, your code is vulnerable to SQL injection attacks. Read up on using PDO for database interaction .
Some more recommended reading to put you on the right track: http://www.phptherightway.com/#databases
EDIT: From what you have shown in your code sample, you simply output an HTML page to the browser, which gets downloaded right away because of the Content-Disposition
header you set.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.