Export MySQL data to Excel in PHP

Introduction to Excel :

Daniel Bricklin and Bob Frankston created the first spreadsheet application, VisiCalc (for “visible calculator”). Lotus 1-2-3 came next, followed by Microsoft Excel. While Lotus 1-2-3 was the first to introduce cell names and macros, Microsoft Excel implemented a graphical user interface and the ability to point and click using a mouse. There are many other spreadsheet applications on the market today; however, Lotus 1-2-3 and Microsoft Excel continue to be the most popular.

About Spreadsheet Application :

A spreadsheet is an interactive computer application program for organization, analysis and storage of data in tabular form. Spreadsheets developed as computerized simulations of paper accounting worksheets. The program operates on data represented as cells of an array, organized in rows and columns. Each cell of the array is a model–view–controller element[dubious – discuss] that may contain either numeric or text data, or the results of formulas that automatically calculate and display a value based on the contents of other cells.

Spreadsheet users may adjust any stored value and observe the effects on calculated values. This makes the spreadsheet useful for “what-if” analysis since many cases can be rapidly investigated without manual recalculation. Modern spreadsheet software can have multiple interacting sheets, and can display data either as text and numerals, or in graphical form.

Here is the PHP Sample Code to Export MySQL Data into Excel / Spreadsheet File :

<?php
/*******EDIT LINES 3-8*******/
$DB_Server = "localhost"; //MySQL Server    
$DB_Username = "username"; //MySQL Username     
$DB_Password = "password";             //MySQL Password     
$DB_DBName = "databasename";         //MySQL Database Name  
$DB_TBLName = "tablename"; //MySQL Table Name   
$filename = "excelfilename";         //File Name
/*******YOU DO NOT NEED TO EDIT ANYTHING BELOW THIS LINE*******/    
//create MySQL connection   
$sql = "Select * from $DB_TBLName";
$Connect = @mysql_connect($DB_Server, $DB_Username, $DB_Password) or die("Couldn't connect to MySQL:<br>" . mysql_error() . "<br>" . mysql_errno());
//select database   
$Db = @mysql_select_db($DB_DBName, $Connect) or die("Couldn't select database:<br>" . mysql_error(). "<br>" . mysql_errno());   
//execute query 
$result = @mysql_query($sql,$Connect) or die("Couldn't execute query:<br>" . mysql_error(). "<br>" . mysql_errno());    
$file_ending = "xls";
//header info for browser
header("Content-Type: application/xls");    
header("Content-Disposition: attachment; filename=$filename.xls");  
header("Pragma: no-cache"); 
header("Expires: 0");
/*******Start of Formatting for Excel*******/   
//define separator (defines columns in excel & tabs in word)
$sep = "\t"; //tabbed character
//start of printing column names as names of MySQL fields
for ($i = 0; $i < mysql_num_fields($result); $i++) {
echo mysql_field_name($result,$i) . "\t";
}
print("\n");    
//end of printing column names  
//start while loop to get data
    while($row = mysql_fetch_row($result))
    {
        $schema_insert = "";
        for($j=0; $j<mysql_num_fields($result);$j++)
        {
            if(!isset($row[$j]))
                $schema_insert .= "NULL".$sep;
            elseif ($row[$j] != "")
                $schema_insert .= "$row[$j]".$sep;
            else
                $schema_insert .= "".$sep;
        }
        $schema_insert = str_replace($sep."$", "", $schema_insert);
        $schema_insert = preg_replace("/\r\n|\n\r|\n|\r/", " ", $schema_insert);
        $schema_insert .= "\t";
        print(trim($schema_insert));
        print "\n";
    }   
?>

30 responses to “Export MySQL data to Excel in PHP”

  1. 1x Avatar

    [1685]1x Official Login বাংলাদেশ | বিকাশ পেমেন্ট ও সেরা ক্যাসিনো বোনাস,1x অ্যাপ ডাউনলোড করে সেরা স্লট গেমের অভিজ্ঞতা নিন। বিকাশ দিয়ে সহজ পেমেন্ট এবং আকর্ষণীয় অনলাইন ক্যাসিনো বোনাস পেতে আজই লগইন করুন। visit: 1x

  2. c9tayaapp Avatar

    Got the C9TayaApp on me phone now. It is okay. Does what it says on the tin. Give it a look if you fancy at c9tayaapp

  3. ki888phcom Avatar

    Best platform for local players in my opinion. Everything feels very tailored to what we want. Visit ki888phcom for a great time.

  4. mega world Avatar

    [554]Mega World Official Login | সেরা অনলাইন ক্যাসিনো ও স্লট গেম,mega world-এ লগইন করে সেরা অনলাইন ক্যাসিনো ও স্লট গেমের অভিজ্ঞতা নিন। বিকাশ দিয়ে টাকা জমা করে সহজেই খেলা শুরু করুন এবং অ্যাপটি ডাউনলোড করুন। visit: mega world

  5. pistolocasino Avatar

    [9340]pistolocasino অফিসিয়াল লগইন | বিকাশ পেমেন্ট ও সেরা বোনাস,pistolocasino অ্যাপ ডাউনলোড করে সেরা স্লট গেমের নিয়ম জানুন এবং বিকাশ দিয়ে সহজে লেনদেন করে আকর্ষণীয় বোনাস পান। আজই জয়েন করুন। visit: pistolocasino

  6. vn89bet9com Avatar

    The betting options here are top notch. I feel much more confident playing on this site. Big shoutout to vn89bet9com for the great service!

  7. 1963bettop Avatar

    What I enjoy most about this site is how effortlessly I can jump into a match without waiting for pages to load. The sportsbook covers everything I follow and the live betting features are genuinely useful. Withdrawal requests get processed on time every single time. If you want a dependable betting buddy this is it. 1963bettop

  8. dv88bet Avatar

    Been checking out dv88bet lately and it seems pretty good. Decent interface, good odds, and it’s easy to use. Seems legit, and I’m having fun. You shold try it: dv88bet

  9. phbeeph Avatar

    Really impressed with the security and transparency of this platform. I feel safe depositing my funds here. Trust phbeeph for your gaming.

  10. vnqq8 Avatar

    Solid experience so far. Everything from registration to depositing was a breeze. Give vnqq8 a try, you won’t regret it.

  11. swertewinslot Avatar

    The slot mechanics are fair and the wins feel genuine. I just hit a decent jackpot on swertewinslot!

  12. sacasinobet Avatar

    Finally a site that actually puts players first. The betting options are diverse, the odds are fair, and I never wait too long for my rewards. Truly a comforting spot to relax and enjoy the thrill of the game. sacasinobet

  13. pdc88 Avatar

    [525]pdc88 লগইন ও অ্যাপ ডাউনলোড – বিকাশ দিয়ে অনলাইন স্লট গেম,pdc88 login করুন এবং বাংলাদেশ সেরা স্লট গেমগুলো উপভোগ করুন। বিকাশ দিয়ে অনলাইন ক্যাসিনো ডিপোজিট করে সহজেই রুলেট খেলার নিয়ম জানুন ও শুরু করুন। visit: pdc88

  14. linkokwin Avatar

    Accessing this site through a single steady link makes the whole betting routine so much calmer. I do not have to chase mirrors or deal with broken pages which saves serious time. The platform keeps the connection working perfectly and the user experience stays smooth across every device. Click to start your winning streak now linkokwin

  15. aaabetplataformaapp Avatar

    The app version is a game changer. I can play wherever I want without any glitches. Seriously, download aaabetplataformaapp right now.

  16. muliajitulogin Avatar

    Super reliable site. I’ve had some issues with other links before but this login page is stable and secure. Happy with the service at muliajitulogin.

  17. 666bet Avatar

    [1168]666bet Login PH | Legit Online Slots at Gcash Casino,Mag-666bet login ph na para sa legit online slots ph. Download 666bet app at subukan ang pinaka mabilis na gcash casino. Mag-register at maglaro na! visit: 666bet

  18. ecbackofficeecuabet Avatar

    I needed a reliable platform for Ecuadorian players and this one fits the bill perfectly. The local payment options are spot on and the interface supports Spanish and English smoothly. I love how transparent the bonus terms are and how quick the verification process goes. The support team responds fast and treats everyone with respect. It feels like a homegrown project that genuinely cares about its users. ecbackofficeecuabet

  19. bd07777 Avatar

    Playing here has been such a smooth ride and I really respect how secure everything feels. The payment options are flexible and my winnings hit my account faster than expected. Make sure you explore bd07777 before you play anywhere else.

  20. oke88 Avatar

    [603]Oke88 | Link vào chính thức và hướng dẫn chơi baccarat online,Truy cập oke88 để tải app nhanh chóng và trải nghiệm nạp tiền casino qua momo tiện lợi. Khám phá kinh nghiệm quay slot nổ hũ thắng lớn. Tham gia ngay hôm nay! visit: oke88

  21. ligastavok Avatar

    [8195]ligastavok লগইন এবং অ্যাপ ডাউনলোড | বিকাশ অনলাইন ক্যাসিনো,ligastavok লগইন করুন এবং বাংলাদেশ সেরা স্লট গেমগুলো উপভোগ করুন। বিকাশ দিয়ে অনলাইন ক্যাসিনো ট্রানজ্যাকশন এবং অ্যাপ ডাউনলোড করতে আজই জয়েন করুন। visit: ligastavok

  22. vn188beet Avatar

    Really impressed with the game variety here. I had a great run last night and the support team was helpful. Highly recommend vn188beet for anyone looking for action.

  23. pinnacleapuestas Avatar

    The odds here are incredibly fair and the layout makes everything so easy to navigate. I love how the team respects player time with quick verification and instant transfers. A solid pick. pinnacleapuestas

  24. 10jiliclublogin Avatar

    I have been playing here for a few months now and the experience is absolutely smooth. The registration process is quick and I love how easy it is to grab the welcome bonus. Customer support responded to my query in under ten minutes which really made my day. If you are looking for a reliable spot to spin the reels, just give this platform a try. 10jiliclublogin

  25. hannonlinecasino Avatar

    Loving the vibe of this place! The bonuses are generous and it feels just like a real casino from the comfort of my home. Give hannonlinecasino a try!

  26. jili49login Avatar

    Easy to navigate and the mobile version works perfectly. I can play anywhere without any lag. Love jili49login

  27. ngoche Avatar

    [8152]Ngoche | Link vào tải app và chơi quay hũ đổi thưởng,Truy cập ngoche để trải nghiệm game quay hũ đổi thưởng hấp dẫn. Hướng dẫn cách chơi baccarat online và nạp tiền casino qua momo nhanh chóng. Tham gia ngay! visit: ngoche

  28. h2m Avatar

    [4818]h2m Login Malaysia | Trusted Online Slot Site & App APK,h2m offers a seamless experience for players. Download the h2m app APK or casino deposit via touch n go to start. Learn how to play baccarat online now. visit: h2m

  29. mexbet Avatar

    [7305]MexBet México: Registro, Login, Bono y Descarga de APK Oficial,Únete a MexBet México, la plataforma líder en apuestas deportivas y casino online. Realiza tu registro hoy mismo, accede a tu login y aprovecha el mejor bono de bienvenida. ¡Descarga la APK oficial y apuesta desde tu móvil con total seguridad y emoción! visit: mexbet

  30. bji88 Avatar

    [5521]bji88 | Link Vào Mới Nhất – Hướng Dẫn Chơi Baccarat Online,bji88 cung cấp đường dẫn truy cập an toàn, hỗ trợ tải app chính thức và hướng dẫn nạp tiền qua Momo nhanh chóng. Khám phá ngay thế giới casino trực tuyến đẳng cấp. visit: bji88

Leave a Reply

Your email address will not be published. Required fields are marked *