Database Code

  Home arrow Database Code arrow Data extract to Excel

Data extract to Excel
By: Codewalkers
  • Search For More Articles!
  • Disclaimer
  • Author Terms
  • Rating: 4 stars4 stars4 stars4 stars4 stars / 21

    Table of Contents:



    Use to extract table data to an excel file directly to your desktop.

    By : wilded1

    // ********************************************************
    // ********** Extract data from mysql table ***************
    // ********** Download Excel file to your PC **************
    $dbhost = "localhost"; // Usually localhost.
    $dbname = ""; // Database name.
    $dbuser = ""; // Database username.
    $dbpass = ""; // Database password.
    $dataname = "website-data"; // FILENAME PREFIX THAT WILL BE ADDED TO XL FILE.
    $tablename = ""; // name of table to extract data from.
    $fields = ""; // the fields in the table you want. seperated with comma. Example ($fields = "field1, field2, field3";)
    /////////// DO NOT EDIT THIS PART OF FILE ////////
    $datestamp = date("d-m-Y");
    $dbh=mysql_connect ($dbhost, $dbuser, $dbpass) or die ('I cannot connect to the database because: ' . mysql_error());
    mysql_select_db ($dbname);
    $query = ("SELECT $fields FROM $tablename");
    $result=mysql_query($query) or die('Error, unsuccesseful when querying database');
    $tsv = array();
    while($row = mysql_fetch_array($result, MYSQL_NUM))
    $tsv[] = implode("\t", $row);
    $tsv = implode("\r\n", $tsv);
    $filename = "$dataname-$datestamp.xls";
    header("Content-type: application/");
    header("Content-Disposition: attachment; filename=$filename");
    echo $tsv;
    DISCLAIMER: The content provided in this article is not warranted or guaranteed by Developer Shed, Inc. The content provided is intended for entertainment and/or educational purposes in order to introduce to the reader key ideas, concepts, and/or product reviews. As such it is incumbent upon the reader to employ real-world tactics for security and implementation of best practices. We are not liable for any negative consequences that may result from implementing any information covered in our articles or tutorials. If this is a hardware review, it is not recommended to open and/or modify your hardware.

    More Database Code Articles
    More By Codewalkers

    blog comments powered by Disqus


    - Converting CSV Files to MySQL Insert Queries...
    - Examples and Tools for Database Design
    - Relationships, Entities and Database Design
    - Modeling and Designing Databases
    - Data extract to Excel
    - Oracle database class 0.76
    - The opposite of mysql_fetch_assoc
    - On line Thermal Transmitance Calculation
    - pjjTextBase
    - PHP Object Generator
    - FastMySQL
    - RC4PHP
    - SQL function with integrated sprintf()
    - DB Interaction Classes v1.1
    - deeMySQLParser

    Developer Shed Affiliates


    © 2003-2019 by Developer Shed. All rights reserved. DS Cluster - Follow our Sitemap