How do I cover this connection and code with the DB for PDO with utf-8 charset? [duplicate]

1
  

My question was not clear, I edited the title, it looked just about UTF-8, but it is not, it's a connection and query conversion to PDO   with UTF-8

<?php  
      //export.php  
 if(isset($_POST["export"]))  
 {  
      $connect = mysqli_connect("localhost", "root", "", "simrede"); 

      header('Content-Type: text/csv; charset=utf-8');  
      header('Content-Disposition: attachment; filename=Cadastro_Alunos-Simrede.csv');  
      $output = fopen("php://output", "w");  
      fputcsv($output, array('lastname', 'firstname', 'department', 'institution', 'username',  'email', 'city', 'course1', 'password'));  
      $query = "SELECT * from cs_alunos ORDER BY institution";  
      $result = mysqli_query($connect, $query);  
      while($row = mysqli_fetch_assoc($result))  
      {
           fputcsv($output, $row);  
      }  
      fclose($output);  
 }  
 ?>  
    
asked by anonymous 12.08.2018 / 04:20

1 answer

2

The PDO connection is simple, to leave it as utf8 just use the code below.

   <?php  
      //export.php  
 if(isset($_POST["export"]))  
 {  
    try {

        $host  = "localhost";
        $user  = "root";
        $pass  = "root";
        $dbname = "db";

        $con = new PDO("mysql:host=$host;dbname=$dbname;charset=utf8", $user, $pass);

        header('Content-Type: text/csv; charset=utf-8');  
        header('Content-Disposition: attachment; filename=Cadastro_Alunos-Simrede.csv');

        $output = fopen("php://output", "w");  

        fputcsv($output, array('lastname', 'firstname', 'department', 'institution', 'username',  'email', 'city', 'course1', 'password'));  

        $query = "SELECT * from cs_alunos ORDER BY institution";  

        $result = $con->query($query);  
        $alunos = $result->fetch(PDO::FETCH_ASSOC);

        foreach($alunos as $aluno)
        {
            fputcsv($output, $aluno["seu_campo_que_retorna_da_query"]);  
        }

        fclose($output); 

    }catch(PDOException $e){

        echo $e->getMessage();  
    } 
 }  
 ?>  
    
12.08.2018 / 05:17