Roland
Roland

Reputation: 9731

Export MySql table to CSV?

So, I have searched most of the answers here on stack and google and anywhere I could think of. There are plenty of answers indeed, but none have the structure I need.

Al my code looks like this:

$sql   = "SELECT * FROM users WHERE user_level = '$level' ORDER BY user_username DESC";
    if ($stmt = $this->connect->prepare($sql)) {
        $stmt->bind_result($id);
        $stmt->execute();
        while ($row = $stmt->fetch()) {
            $stmt->bind_result($id);
            $users[] = $id;
        }
        $stmt->close();
        $length[] = sizeof($users);
    } else {
        $error              = true;
        $message['error']   = true;
        $message['message'] = CANNOT_PREPARE_DATABASE_CONNECTION_MESSAGE;
        return json_encode($message);
    }

I'm using mysqli and stmt in all of my code, so I would like to keep it like this all the way.

So, I understand that I cannot have the CSV file where I have my action button to download it. But the thing is that my action button is part of a form, so I guess that instead of $_GET on the page I have the CSV I will have $_POST.

And my question, how do I loop through all database ( this needs to be depending on a column, a level ) and take all that data organized in a CSV file and than download it ? But this needs to be as the structure I have for my functions, I don't want to use db_query("SELECT * FROM {loreal_salons}"); per say or other like that.

Upvotes: 0

Views: 908

Answers (2)

Manse
Manse

Reputation: 38147

Use the following :

// Setup the headers to force download of CSV
header("Content-type: application/csv");
header("Content-Disposition: attachment; filename=file.csv");
header("Pragma: no-cache");
header("Expires: 0");


// loop your records here and output as comma separated
echo $row['col1'].",".$row['col3'].",".$row['col3']."\n";

Upvotes: 1

FMaz008
FMaz008

Reputation: 11295

If you want to loop over all the database, I think the key for what you want to do is :

SHOW TABLES - http://dev.mysql.com/doc/refman/4.1/en/show-tables.html .. to loop in all the tables

SHOW COLUMN - http://dev.mysql.com/doc/refman/5.0/en/show-columns.html .. to loop in all the column of a specific table

Upvotes: 0

Related Questions