[Last Call] Learn how to a build a cloud-first strategyRegister Now

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 87
  • Last Modified:

Export MYSQL to .CSV Add Column Names PHP

Here is my code to export my MySQL table to .csv. How do I add the column names to it ? Thanks

<?php
    // mysql database connection details
    $host = "localhost";
    $username = "";
    $password = "";
    $dbname = "";

    // open connection to mysql database
    $connection = mysqli_connect($host, $username, $password, $dbname) or die("Connection Error " . mysqli_error($connection));
    
    // fetch mysql table rows
    $sql = "select * from masterbrewlist";
    $result = mysqli_query($connection, $sql) or die("Selection Error " . mysqli_error($connection));

    $fp = fopen('masterlist.csv', 'w');

    while($row = mysqli_fetch_assoc($result))
    {
        fputcsv($fp, $row);
    }
    
    fclose($fp);

    //close the db connection
    mysqli_close($connection);
?>

Open in new window

0
Ray Zuchowski
Asked:
Ray Zuchowski
1 Solution
 
JesterTooCommented:
Notice I've given some values to $username, $password, and $dbname.

<?php
    // mysql database connection details
    $host = "localhost";
    $username = "lynn";
    $password = "gauge";
    $dbname = "alphacrm";
    $first = true;

    // open connection to mysql database
    $connection = mysqli_connect($host, $username, $password, $dbname)
       or die("Connection Error " . mysqli_error($connection));

    // fetch mysql table rows
    $sql = "select * from tcompany";
    $result = mysqli_query($connection, $sql)
       or die("Selection Error " . mysqli_error($connection));

    $fp = fopen('masterlist.csv', 'w');

    while($row = mysqli_fetch_assoc($result))
    {
        if ($first) {
           $first = false;
           fputcsv($fp, array_keys($row));
        }
        fputcsv($fp, $row);
    }

    fclose($fp);

    //close the db connection
    mysqli_close($connection);
?>

Open in new window

1
 
Ray ZuchowskiInformation Systems ManagerAuthor Commented:
Excellent. Thanks
0

Featured Post

What does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now