php - Generating a CSV download using PDO queries -
i trying make user able download csv backup of of data on server. means trying execute multiple query's , placing results csv file.
this have far:
<?php // connect include 'config.php'; // config contains pdo database connection, etc. // generate filename $filename = $_session['current_group'].'-'.date('d.m.y').'.csv'; // backup data mysql database $result_users = $conn->prepare('select `user_name`, `user_email` `users` `group_id` = ?'); $result_users->execute(array($_session['current_group_id'])); $result_items = $conn->prepare('select `item_name`, `item_value`, `item_group` `items` `group_id` = ?'); $result_items->execute(array($_session['current_group_id'])); # create array $list = array ("## start of user table ##"); // append results array while ($row = $result_users->fetch(pdo::fetch_assoc)) { array_push($list, array_values($row)); } array_push($list,"## end of user table ##"); array_push($list,"## start of items table ##"); while ($row = $result_items->fetch(pdo::fetch_assoc)) { array_push($list, array_values($row)); } array_push($list,"## end of items table ##"); // output array csv file $fp = fopen('php://output', 'w'); header('content-type: text/csv'); header('content-disposition: attachment; filename="'.$filename.'"'); foreach ($list $ferow) { fputcsv($fp, split(',',$ferow)); } ?> the expected output supposed like:
## start of users table ## "john","john@email.com" "james","james@email.com" ## end of users table ## ## start of items table ## "soap","a lot","household" "banana","2","food" ## end of items table ## etc.
the problem valued not correctly pushed $list array. should in order wanted result?
thanks!
i think code little complicated need. don't test code works
$sql = "select user_name, user_email users group_id = :group_id union select item_name, item_value, item_group items group_id = :group_id "; $sth = $conn->prepare($sql); $sth->bindvalue(':group_id', $_session['current_group_id'], pdo::param_int); $sth->execute(); $filename = $_session['current_group'].'-'.date('d.m.y').'.csv'; $data = fopen($filename, 'w'); while ($row = $sth->fetch(pdo::fetch_assoc)) { fputcsv($data, $row); } fclose($data);
Comments
Post a Comment