How to cover this connection and code with DB for PDO with charset utf-8?

Asked

Viewed 182 times

1

My question was not clear, I edited the title, it seemed only about UTF-8, but it is not, it is 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);  
 }  
 ?>  

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();  
    } 
 }  
 ?>  
  • 2

    In addition to the connection, enter the rest of the code. prepare() execute() fetchall() . I think that’s what he wants too.

  • @William the PDO connection I know how it is, what I want to know is how is the remaining code, because it is not enough to just change the connection.

  • @Miguelsilva then I’m not quite sure what you’re planning to do with this code, but there’s the rest of it edited into the answer. ( PS: If you want to convert these records into an excel spreadsheet I suggest using some lib like the Phpspreadsheet.)

  • @William this code exports a DB table in CSV format, did not understand what to put in "seu_campo_que_retorna_da_query"

  • The Code is working fine, I would just like to upgrade to an updated version of the connection and consequently the rest of the code

Browser other questions tagged

You are not signed in. Login or sign up in order to post.