我以csv格式显示我的数据库,但我也无法弄清楚如何导出mysql表列名。这是代码:
public function save($query)
{
$stmt = $this->db->prepare($query);
$stmt->execute();
/* header("Content-type: text/csv");
header("Content-Disposition: attachment; filename=file.csv");
header("Pragma: no-cache");
header("Expires: 0");
var_dump($stmt->fetch(PDO::FETCH_ASSOC));
$data = fopen('/tmp/db_user_export_".time().".csv', 'w');
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)){
echo "Success";
fputcsv($data, $row);
} */
$list = array ();
// Append results to array
array_push($list, array("## START OF USER TABLE ##"));
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
array_push($list, array_values($row));
}
array_push($list, array("## END OF USER TABLE ##"));
// Output array into CSV file
$fp = fopen('php://output', 'w');
header('Content-Type: text/csv');
header('Content-Disposition: attachment; filename="file.csv"');
foreach ($list as $ferow) {
fputcsv($fp, $ferow);
}
}
查询:
include_once 'dbconfig.php';
$query = "SELECT * FROM users";
$crud->save($query);
file.csv导出正确,但我还想包括从中取出值的mysql表列的名称。
提前致谢!
答案 0 :(得分:0)
我有问题将我的表头发布到csv中,所以我采取了另一种方法。希望它可以帮助那些试图做我正在做的事情的人:
public function export($table)
{
$stmt2 = $this->db->prepare("DESCRIBE ".$table);
$stmt2->execute();
if ($stmt2->rowCount()>0) {
while ($row = $stmt2->fetch(PDO::FETCH_ASSOC)) {
$csv_output .= $row['Field'].", ";
$i++;
}
}
$csv_output .= "\n";
$stmt3 = $this->db->prepare("SELECT * FROM ".$table);
$stmt3->execute();
while ($rowr = $stmt3->fetch(PDO::FETCH_BOTH)) {
for ($j=0;$j<$i;$j++) {
$csv_output .= $rowr[$j].", ";
}
$csv_output .= "\n";
}
$filename = "raport_proiecte_".date("Y-m-d_H-i",time()).".csv";
header("Content-Type: application/xls");
header("Content-Disposition: attachment; filename=$filename");
header("Pragma: no-cache");
header("Expires: 0");
print $csv_output;
exit;
}