我正在尝试以csv格式输出数据库选定的行,但它输出重复的值而不是单个值。我希望它有列和列下面的值。输出: onlineId,paramId,paramValue 4cd87b00dddca780fcaf66d0108b25f6,4cd87b00dddca780fcaf66d0108b25f6,1,1,11,11
以下代码:
$output = fopen('php://output', 'w');
fputcsv($output, array('onlineId', 'paramId', 'paramValue'));
$host = "localhost";
$database = "keytarget";
$username = "root";
$password = "";
$con = new PDO("mysql:host=" . $host . ";dbname=" . $database, $username, $password);
//Run our query
$sql = "
SELECT
ui.onlineId, uin.paramId, uin.paramValue
FROM
v5_userinfo ui
JOIN
v5_userinfo_number uin
ON
uin.userId = ui.id
;
";
$statement = $con->prepare($sql);
$statement->execute();
while ($row = $statement->fetch()) {
fputcsv($output, $row);
}
答案 0 :(得分:0)
当你检索数据时,它会在关联数组和普通数组More info之间混合。所以你的$ row var类似于:
array(
[0]=>4cd87b00dddca780fcaf66d0108b25f6
[onlineId]=>4cd87b00dddca780fcaf66d0108b25f6
[1]=>1
[paramId]=>1
[2]=>11
[paramValue]=>11
)
所以你的解决方案可能是:
while ($row = $statement->fetch()) {
$array=array($row[0],$row[1],$row[2]);
fputcsv($output, $array);
}
或者更容易:
while ($row = $statement->fetch(PDO::FETCH_ASSOC)) {
fputcsv($output, $row);
}