How to output an entire table from MYSQL?

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
User avatar
becky-atlanta
Forum Commoner
Posts: 74
Joined: Thu Feb 26, 2009 6:26 pm
Location: Atlanta, GA

How to output an entire table from MYSQL?

Post by becky-atlanta »

I have a large table that I would like to display on a web page as a table or export it to a CSV format file. Does MYSQL have a function/command which allows me to output the entire table? I just try to see if I can get away from typing all 44 field names. Is it possible?
alexpaul_v
Forum Newbie
Posts: 3
Joined: Wed Jan 30, 2008 4:55 am

Re: How to output an entire table from MYSQL?

Post by alexpaul_v »

if you need the column ( field ) names of a table, then you can use this query: "SHOW COLUMNS FROM <table name>"
Mark Baker
Forum Regular
Posts: 710
Joined: Thu Oct 30, 2008 6:24 pm

Re: How to output an entire table from MYSQL?

Post by Mark Baker »

You don't need to type the actual field names at all.

Code: Select all

 
$csvFile = fopen('myTable.csv','w');
$query = "select * from myTable";
$result = mysql_query($query);
while ($row = mysql_fetch_assoc($result)) {
   $csvArray = array();
   foreach($row as $value) {
      $csvArray[] = $value;
   }
   fputcsv($csvFile,$csvArray);
}
fclose($csvFile);
 
User avatar
becky-atlanta
Forum Commoner
Posts: 74
Joined: Thu Feb 26, 2009 6:26 pm
Location: Atlanta, GA

Re: How to output an entire table from MYSQL?

Post by becky-atlanta »

Thank you, alexpaul and Mark. You both gave excellent advice. I was able to do what I want in a much more efficient way. Thanks again!
Post Reply