I have a script that I have modified to export a MySQL table to an Excel File. The script works except for the fact that it duplicates every element.

For example, if I have a record that consists of:

firstName = John
lastName = Doe
email = john@email.com

The output will be:

John John Doe Doe john@email.com john@email.com

It will do this for every record in the table. Here is the code:

//Config file holds all connection information
require_once('config.php');  

// Connect to DB
$conn = mysql_connect(LOCATION,USERNAME,PASSWORD);
if (!$conn) die ("Cannot connect MySQL");	

// execute connection string
mysql_select_db(DATABASE,$conn) or die ("Could not open database");

$result = mysql_query("select * from tblContacts"); 

$tsv_output = array();

   while($row = mysql_fetch_array($result)) { 

   $tsv_output[] = implode("\t", $row);

   } 

$tsv_output = implode("\r\n", $tsv_output);

$fileName = 'registrations.xls';
header("Content-type: application/vnd.ms-excel"); 
header("Content-Disposition: attachment; filename=$fileName");

echo $tsv_output;

    Because you used "mysql_fetch_array($result))" which returns both an associated and numerical array.

    Try:
    mysql_fetch_row() or
    mysql_fetch_assoc()

    instead.

      Both work like a charm! Thank you!

      Can you explain the array a little bit more? Why does fetch_array() return associated & numerical? What is advantage of this and how does it work? What is the numerical data and how was that causing a duplication?

        Arrays are a great way to toss data around your program in an organized fashion. I use them more than any other data type. There is much to learn about arrays and I have to refer you to the php manual for that.

        See: http://us3.php.net/manual/en/function.mysql-fetch-array.php
        and
        http://us3.php.net/manual/en/function.mysql-fetch-assoc.php
        and
        http://us3.php.net/manual/en/function.mysql-fetch-row.php

        I would hazard a guess that mysql_fetch_array() might have come first and then assoc and row where added later to the language. I just learned that you can specify MYSQL_ASSOC, MYSQL_NUM, or MYSQL_BOTH in mysql_fetch_array() to achieve the same results as assoc and row.

        Happy Coding...🙂

          Write a Reply...