Home > other >  MYSQL PHP exports csv to one column! Hove to export in to separated columns?
MYSQL PHP exports csv to one column! Hove to export in to separated columns?

Time:11-08

I need help to find why is exporting this way and how to fix it?

my code exportes this way:

enter image description here

The goal is to get this:

enter image description here

code:

    include 'settings.php';

 if(isset($_POST["export"]))  
 {   
    $filename = "adat_" . date('Y-m-d') . ".csv";
    $delimiter = ",";

    header('Content-Type: text/csv'); 
    header('Content-Disposition: attachment; filename="' . $filename . '";'); 
    
      $output = fopen("php://output", "w");  
      fputcsv($output, array('barcode', 'name', 'status', 'log_in', 'log_out'), $delimiter);  
      $query = 
      "SELECT userlog.barcode, workers.name, workers.status, userlog.log_in, userlog.log_out
      FROM userlog
      INNER JOIN workers 
      ON workers.barcode=userlog.barcode"; 

      $result = mysqli_query($conn, $query);  
      while($row = mysqli_fetch_assoc($result))  
      {  
           fputcsv($output, $row);  
      }  
      fclose($output);  
 }  
?>  

CodePudding user response:

The code is OK and export is OK, but you need to set "," separator to Google Sheet or Excel.

If you use Google Sheet, don't copy text from CSV, do import, and press auto detect separator.

CodePudding user response:

This is the solution for the problem! Thx for the help!

    include 'settings.php';

 if(isset($_POST["export"]))  
 {   
    $sql_query = "SELECT userlog.barcode, workers.name, workers.status, userlog.log_in, userlog.log_out
         FROM userlog
         INNER JOIN workers 
         ON workers.barcode=userlog.barcode";
    $resultset = mysqli_query($conn, $sql_query) or die("database error:". mysqli_error($conn));
    $developer_records = array();
    while( $rows = mysqli_fetch_assoc($resultset) ) {
        $developer_records[] = $rows;
    }   
   
   
    $filename = "phpzag_data_export_".date('Ymd') . ".xls";         
    header("Content-Type: application/vnd.ms-excel");
    header("Content-Disposition: attachment; filename=\"$filename\"");  
    $show_coloumn = false;
    if(!empty($developer_records)) {
      foreach($developer_records as $record) {
        if(!$show_coloumn) {
          // display field/column names in first row
          echo implode("\t", array_keys($record)) . "\n";
          $show_coloumn = true;
        }
        echo implode("\t", array_values($record)) . "\n";
      }
    }
    exit;
 }  
?>  ```
  • Related