[英]Export data from SQL to CSV with modified format
Suppose I have a table in SQL named 'myTable'. 假设我在SQL中有一个名为“ myTable”的表。 It contains 3 columns;
它包含3列; 'id', 'lat' and 'lng'
'id','lat'和'lng'
| id | lat | lng |
|------+--------+--------|
| 1 | 1.11 | 1.22 |
| 2 | 2.11 | 2.22 |
| 3 | 3.11 | 3.22 |
| 4 | 4.11 | 4.22 |
| .... | .... | .... |
I want to export it to CSV. 我想将其导出为CSV。 I expect the result become like this in the CSV file :
我希望结果在CSV文件中变成这样:
| | A | B | C | D | ....
------+-----+------+--------+------+--------
| 1 | 1.11 | 2.11 | 3.11 | 4.11 | .... //contains 'lat'
| 2 | 1.22 | 2.22 | 3.22 | 4.22 | .... //contains 'lng'
Can you help me? 你能帮助我吗? I'm using PHP.
我正在使用PHP。 Thanks a lot.
非常感谢。
This might actually be something which would be best handled in your PHP script, rather than in MySQL. 实际上,这可能是最好在您的PHP脚本中而不是在MySQL中处理的东西。 Assuming your are using
mysqli
, you could try something like this: 假设您正在使用
mysqli
,则可以尝试如下操作:
$sql = "SELECT id, lat, lng FROM yourTable ORDER BY id";
$result = $conn->query($sql);
$row1 = NULL;
$row2 = NULL;
if ($result->num_rows > 0) {
while ($row = $result->fetch_assoc()) {
if ($row1 != NULL) {
$row1 .= ",";
$row2 .= ",";
}
$row1 .= $row["lat"];
$row2 .= $row["lng"];
}
}
At the end of the loop in the above script, $row1
and $row2
should contain the first two rows of the output file you expect. 在以上脚本的循环结束时,
$row1
和$row2
应该包含您期望的输出文件的前两行。 The only steps missing might be the header, if you want that, and also the details of how to write a string to a text file. 如果需要的话,缺少的唯一步骤可能是标题,以及如何将字符串写入文本文件的详细信息。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.