What are some best practices for structuring PHP queries to efficiently retrieve hierarchical data from a MSSql database?

When retrieving hierarchical data from a MSSQL database in PHP, it is best practice to use recursive queries to efficiently fetch the data in a hierarchical structure. This can be achieved by using Common Table Expressions (CTE) in MSSQL to recursively query the data and then fetch it in a nested array format in PHP.

// Establish a connection to the MSSQL database
$serverName = "your_server_name";
$connectionOptions = array(
    "Database" => "your_database_name",
    "Uid" => "your_username",
    "PWD" => "your_password"
);
$conn = sqlsrv_connect($serverName, $connectionOptions);

// Define the recursive query using Common Table Expressions
$sql = "
    WITH RecursiveCTE AS (
        SELECT id, name, parent_id
        FROM your_table_name
        WHERE parent_id IS NULL
        UNION ALL
        SELECT t.id, t.name, t.parent_id
        FROM your_table_name t
        JOIN RecursiveCTE r ON t.parent_id = r.id
    )
    SELECT id, name, parent_id
    FROM RecursiveCTE
";

// Execute the query and fetch the hierarchical data
$stmt = sqlsrv_query($conn, $sql);
$hierarchicalData = array();
while ($row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC)) {
    $hierarchicalData[$row['id']] = array(
        'name' => $row['name'],
        'parent_id' => $row['parent_id']
    );
}

// Close the database connection
sqlsrv_close($conn);

// Output the hierarchical data
print_r($hierarchicalData);