Backup MySQL data into CSV [Part-2]
In my last article i showed you how to Setup web server on Amazon AMI or CentOS, to continue on that article further i will discuss here how to backup MySQL data into CSV format.
So let’s start, login into your machine through terminal and login to MySQL server and choose database by command use databasename
. Let’s dump a table to csv:
SELECT * INTO OUTFILE '/var/www/html/users.csv' FIELDS TERMINATED BY ',' ENCLOSED BY '"' ESCAPED BY '\\' LINES TERMINATED BY '\n' FROM users;
The above command will output all the columns and data into a csv file which will be saved in /var/www/html, change this according to your need.
Now let’s say we have multiple tables and they are connected with each other through keys. For example user table with votes table.
SELECT 'Name', 'Email', 'Time','Phone','City' UNION SELECT u.name, u.email, FROM_UNIXTIME(v.vote_time, '%M %D %Y - %l:%i %p') AS timestamp, u.phone, u.city INTO OUTFILE '/var/www/html/users_votes.csv' FIELDS TERMINATED BY ',' ENCLOSED BY '"' ESCAPED BY '\\' LINES TERMINATED BY '\n' from users u join votes v on u.uid=v.uid;
We are joining two tables here on uid, which is user id. Name, Time, Phone, Email, City will be the column headers in CSV for each column selected from database. vote_time i assume is stored in db as unix timestamp. That is quite straight and simple, nothing fancy there.
Of course you can join many tables to output your desire data. That’s it for now. In the next article i will show you how to save/download data in CSV format/file using PHP and MySQL with fputcsv function. Stay tune.
Series:
Part-1: Setup web server on Amazon AMI or CentOS
Part-2: Backup MySQL data into CSV
Part-3: Backup MySQL data into CSV with PHP
Part-4: Backup and Restore MySQL databases
Part-5: Speed up your website loading time by using PHP APC