PHP从MySQL导出为CSV

时间:2017-03-03 11:39:56

标签: php mysqli export-to-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

这意味着,导出需要是2名成员,ParentID = 2,但成员迈克琼斯有孩子(杰森威廉姆斯),也需要出口。迈克威廉姆斯也有一个孩子(萨拉约翰逊)也需要出口。换句话说,函数需要查找ParentID = 2的所有成员,但他们也是子项并将它们全部导出。谢谢你的帮助。

3 个答案:

答案 0 :(得分:1)

要查找ID = 2的所有行(即Mike和Amy),只需修改MYSQL语句以包含WHERE子句:

    $sql = 'SELECT NAME, ID, PARENTID from tablename WHERE ID="2"';

要查找ID = 2的所有行,或父级对应ID = 2的行(即Mike,Jason和Amy),您可以使用:

    $sql = 'SELECT t1.NAME FROM test2 AS t1 JOIN test2 AS t2 ON t1.PARENTID = t2.ID WHERE t1.PARENTID = "2" OR t2.PARENTID = "2"';

JOIN执行'递归'位,在PARENTID列中查找值的ID,以便您可以查询行本身的ID和PARENTID对应行的PARENTID的每一行。

对于一个额外的递归水平(即找到Mike,Jason,Amy和Sara),请使用:

    $sql = 'SELECT t1.NAME FROM test2 AS t1 JOIN test2 AS t2 ON t1.PARENTID = t2.ID JOIN test2 AS t3 ON t1.PARENTID = t3.ID WHERE t1.PARENTID = '2' OR t2.PARENTID = '2' OR t3.PARENTID = '3'';

在此解决方案中,您需要为每个级别的递归添加额外的连接。

答案 1 :(得分:1)

$sql = "SELECT NAME, ID, PARENTID from tablename WHERE ID=2";

答案 2 :(得分:0)

 $sql = "SELECT NAME, ID, PARENTID from tablename Where ID='2'";