PHP从MySQL导出到CSV
作者:互联网
我需要将数据从MySQL导出到CSV,但要从特定ID导出.该表包含ID,ParentID和Name,这是导出所有记录的代码:
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "databasename";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$index = array();
$num = 0;
$sql = "SELECT NAME, ID, PARENTID from tablename";
$result = $conn->query($sql);
while($row = $result->fetch_array(MYSQLI_ASSOC)){
$rows[] = $row;
$index[$row['ID']] = $row;
}
$output = fopen("php://output",'w') or die("Can't open php://output");
header("Content-Type:application/csv");
fputcsv($output, array('ID','NAME','PARENTID'));
// build the tree
foreach($index as $id => &$row){
if ($id === 0) continue;
$parent = $row['PARENTID'];
$index[$parent][] = &$row;
fputcsv($output, $row);
}
fclose($output) or die("Can't close php://output");
unset($row);
// start from this ID
$index = $index[2];
/* free result set */
$result->close();
/* close connection */
$conn->close();
如果我在表中有此表(这是表声明):
ID PARENT NAME
1 0 John Doe
2 1 Sally Smith
3 2 Mike Jones
4 3 Jason Williams
5 4 Sara Johnson
6 1 Dave Wilson
7 2 Amy Martin
如何导出parentID = 2(递归)的成员的所有子代?
换句话说,我需要这样的输出:
ID PARENT NAME
3 2 Mike Jones
4 3 Jason Williams
5 4 Sara Johnson
7 2 Amy Martin
这意味着,导出的必须是ParentID = 2的2个成员,但是成员Mike Jones的孩子(Jason Williams)也需要导出.迈克·威廉姆斯还有一个孩子(萨拉·约翰逊),也需要出口.换句话说,函数需要查找ParentID = 2的所有成员,但也要找到所有成员并将其全部导出.谢谢您的帮助.
解决方法:
$sql = "SELECT NAME, ID, PARENTID from tablename WHERE ID=2";
标签:export-to-csv,php,mysqli 来源: https://codeday.me/bug/20191013/1907871.html