I have working code which export records to JSON (please see below) and now I need that records are exported to CSV. Code below have "root node" which means, it will export members with PARENTID=2 and all they children's (recursively). What I need is that exported are records for given PARENTID but in CSV instead in JSON.
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "mydataabse";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$index = array();
$sql = "SELECT NAME, ID, PARENTID FROM mytable";
$result = $conn->query($sql);
while($row = $result->fetch_array(MYSQLI_ASSOC)){
$rows[] = $row;
$index[$row['ID']] = $row;
}
// build the tree
foreach($index as $id => &$row){
if ($id === 0) continue;
$parent = $row['PARENTID'];
$index[$parent]['children'][] = &$row;
}
unset($row);
// root node - exported are members with this PARENTID and all they children's
$index = $index[2]['children'];
/* free result set */
$result->close();
/* close connection */
$conn->close();
// output json
header('Content-Type: application/json');
echo json_encode($index, JSON_PRETTY_PRINT);
Here is mytable structure, if needed:
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
Thank you so much.
Warning: array_unshift() expects parameter 1 to be array, null given in C:\Apps\CSV.php on line 74
Catchable fatal error: Argument 2 passed to exportToCSV() must be of the type array, null given, called in C:\Apps\CSV.php on line 76 and defined in C:\Apps\CSV.php on line 39
– ZMik Mar 03 '17 at 15:46