It seems like you're trying to dynamically retrieve column names from the first loop and then use them to fetch corresponding data from the database in the second loop. However, you're facing issues with the data retrieval part. Let's correct the code:
fputcsv($csvfile, $export_column_name_array, $delimiter);
$stmt2 = $conn->prepare($sql_built_statement);
//$stmt2->bind_param("ii", $company_id, $company_id); WILL ADD THIS LATER ONCE WORKING
$stmt2->execute();
$result2 = $stmt2->get_result();
if($result2 != NULL){
// Retrieve data
while($row2=$result2->fetch_assoc()){
// Initialize an empty data array for each row
$data_array = array();
// Add data for each column
foreach ($export_column_name_array as $value) {
// Push data for each column into the data array
$data_array[] = $row2[$value];
}
// Write the data array to the CSV file
fputcsv($csvfile, $data_array, $delimiter);
}
}
fclose($csvfile);
In this corrected code:
We loop through each row of the fetched data and initialize an empty $data_array for each row.
Within the row loop, we iterate through each column name from $export_column_name_array.
For each column name, we fetch the corresponding data from the $row2 associative array and add it to the $data_array.
After populating the $data_array with data for all columns, we write it to the CSV file using fputcsv().
The process repeats for each row fetched from the database until all rows have been processed.
i hope This should correctly populate your CSV file with the data fetched from the database, using the dynamic column names obtained from $export_column_name_array.
Best Regard
Danish hafeez | QA Assistant
ICTInnovations