【发布时间】:2014-02-18 10:54:40
【问题描述】:
尝试将以下工作代码转换为 PDO,我遇到的问题是 fputcsv($output,array) 中设置的自定义标题。我真的很想摆脱所有 msql_ 函数,因此我将不胜感激。
<?php
// output headers so that the file is downloaded rather than displayed
header('Content-Type: text/csv; charset=utf-8');
header('Content-Disposition: attachment; filename=collections.csv');
// create a file pointer connected to the output stream
$output = fopen('php://output', 'w');
//MySQL Connect
removed
// output the column headings
fputcsv($output, array('Title','InclusiveDates','CollectionID','LocationID','Content','RangeValue','Section','Shelf','Extent','ExtentUnitID'));
// fetch the data
$rows = mysql_query('SELECT
coll.title AS CollectionTitle,
coll.inclusivedates AS InclusiveDates,
coll.ID AS CollectionID,
collloc.LocationID,
collloc.Content,
collloc.RangeValue,
collloc.Section,
collloc.Shelf,
collloc.Extent,
collloc.ExtentUnitID
FROM tblCollections_Collections coll
JOIN tblCollections_CollectionLocationIndex collloc
ON collloc.CollectionID = coll.id
ORDER BY coll.ID');
// loop over the rows, outputting them
while ($row = mysql_fetch_assoc($rows)) fputcsv($output, $row);
?>
我已经走到了这一步,但没有让它工作。这里的问题是我无法在 CSV 文件中设置自定义列名,它也无法导出到 CSV。
<?php
$conn = removed
$query = "SELECT
coll.title AS CollectionTitle,
coll.inclusivedates AS InclusiveDates,
coll.ID AS CollectionID,
collloc.LocationID,
collloc.Content,
collloc.RangeValue,
collloc.Section,
collloc.Shelf,
collloc.Extent,
collloc.ExtentUnitID
FROM tblCollections_Collections coll
JOIN tblCollections_CollectionLocationIndex collloc
ON collloc.CollectionID = coll.id
ORDER BY coll.ID";
$stmt = $conn->prepare($query);
// Execute the statement
$stmt->execute();
var_dump($stmt->fetch(PDO::FETCH_ASSOC));
$data = fopen('file.csv', 'w');
$header = array();
while ($row = $stmt->fetch(PDO::FETCH_ASSOC))
{
if(empty($header)){ // do it only once!
$header = array_keys($row); // get the columnnames
fputcsv($data, $header); // put them in csv
}
echo "Success";
// Export every row to a file
fputcsv($data, $row);
}
?>
【问题讨论】:
-
问题与PDO/mysql有什么关系?在两个脚本中涉及 csv 文件时,您正在做根本不同的事情。
-
不,我只是无法使用 PDO 而不是 mysql_ 产生相同的结果。 :-(
-
你怎么知道的?你已经改变了很多,并且正在输出到不同的媒体,很难判断问题出在哪里。您应该从 just 切换到 PDO 开始,并在该逻辑正常工作时更改其他逻辑。
-
如果我错了,请纠正我,但你不必
fclose文件吗? -
PDO的输出与mysql_的输出相同,即关联数组。因此,从一个更改为另一个应该很简单。 PS因为你没有使用绑定参数,你可以使用query()而不是
prepare()