Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • Discuss on export MySQL Table Records into CSV file

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 370
    Comment on it

    Hi Reader's,
    Welcome to FindNerd, today we are going to discuss export MySQL Table Records into CSV file.

    If we are developing any web application in PHP then sometimes we need to export MySQL Table Records into CSV file. fputcsv() is a function which accepts an array and a file pointer as parameters which convert the array data into CSV format and writes it to the file.

    We can see below example for better understanding. Firstly we will create a file pointer using fopen() and set the value for content-type and content-Disposition in header().
    After creating a file pointer we will pass the file pointer and array of database record into fputcsv() for generating CSV file.

    <?php
      //here we define our database detail
      $host = 'hostname';
      $user = 'username';
      $password = 'password';
      $database = 'databasename';
      $table = 'tablename';
    
        // here get a connection to database
        $con = mysqli_connect($host, $user, $password, $database);
        $filename = "sample.csv";
        $file = fopen('php://output', 'w');
    
        //To fetch column names of table
        $query = "SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA='".$database."' AND TABLE_NAME='".$table."'";
        $result = mysqli_query($con, $query);
        while ($res = mysqli_fetch_row($result)) {
        $header[] = $res[0];
        }
    ?>
    

    Now write  code for generating CSV file

    <?php
        //Generate CSV file
        header('Content-type: application/csv');
        header('Content-Disposition: attachment; filename='.$filename);
        fputcsv($file, $header);
    ?>

    Now write code for retrieving data from database

    <?php
        //To fetch records from table
        $query = "SELECT * FROM $table";
        $result = mysqli_query($con, $query);
        while($data = mysqli_fetch_row($result)){
        fputcsv($file, $data);
        }
        fclose($file);
    ?>

    I hope this blog will help you to export MySQL Table Records into CSV file

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: