Mastering phpMyAdmin 3.3.x for Effective MySQL Management
上QQ阅读APP看书,第一时间看更新

Exporting a database

In the Database view, click on the Export link. The default export panel looks like this:

Exporting a database

The default values selected here depend on config.inc.php, more specifically on the $cfg['Export'] array of parameters. For example, the $cfg['Export']['format'] parameter is set to'sql', so that the SQL export mode is chosen by default.

The export panel has three subpanels. The top panel, Export, and the bottom panel, Save as file, are always there. However, the third panel varies (using dynamic menu techniques) in order to show the options for the export mode chosen (which is SQL here).

The export subpanel

This subpanel contains a table selector, from where we choose the tables and the format that we want. The SQL format is useful for our needs, as it creates standard SQL commands that would work on any SQL server. Other formats are available, depending on our needs.

We shall now discuss the formats (and the options available once they have been chosen) that can be selected in the Export subpanel.

Note

Even if we can export into many formats, only some of these formats can be imported back using phpMyAdmin.

SQL

We will start by clicking on Select All; we want all of the tables. We know that the tables are small, so the on-screen export will not be too large. For the moment, let's deselect the Extended inserts checkbox. To produce an export file, we would normally leave the Save as file checkbox selected, but to see the results on screen, we deselect it; we then click on Go.

The first part of the export comprises comments (starting with the characters --) that detail the utility (and version) that created the file, the date, and other environment information. We then see the CREATE and INSERT queries for each table.

Note

phpMyAdmin generates ANSI-compatible comments in the export file. These comments start with --. They help with importing the file into other ANSI SQL-compatible systems.

Defining options for SQL export

SQL options are used to define exactly what information the export will contain. We may want to see the structure, the data, or both. Selecting Structure generates the section with CREATE queries, and selecting Data produces INSERT queries. The following screenshot depicts the general SQL options and the Structure options:

Defining options for SQL export

The general SQL options are:

  • Add custom comment into header: We can add our own comments for this export (for example, Monthly backup), which will appear in the export headers (after the PHP version number). If the comment has more than one line, we must use the special character \n to separate each line.
  • Comments: Removing the check mark here causes the export to have no comments at all.
  • Enclose export in a transaction: Starting with MySQL 4.0.11, we can use the START TRANSACTION statement. This command, combined with SET AUTOCOMMIT=0 at the beginning and COMMIT at the end, asks MySQL to execute the import (when we will re-import this file) in one transaction, ensuring that all the changes are done as a whole.
  • Disable foreign key checks: In the export file, we can add DROP TABLE statements. However, normally a table cannot be dropped if it's referenced in a foreign key constraint. This option overrides the verification by adding SET FOREIGN_KEY_CHECKS=0 to the export file. This override only lasts for the duration of the export.
  • SQL compatibility mode: This lets us choose the flavor of SQL that we export. We must have some knowledge about the system into which we intend to import this file. Among the choices are MySQL 3.23, MySQL 4.0, Oracle, and ANSI.

The options in the Structure section are:

  • Add DROP TABLE / VIEW / PROCEDURE / FUNCTION / EVENT: Adds a DROP ... IF EXISTS statement before each CREATE statement, for example: DROP TABLE IF EXISTS `author`;. This way, we can ensure that the export file is executed on a database in which the same element already exists, updating its structure but destroying the previous elements' contents.
  • Add IF NOT EXISTS: Adds the IF NOT EXISTS modifier to CREATE TABLE statements, avoiding an error during import if the table already exists.
  • Add AUTO_INCREMENT value: Puts auto-increment information from the tables into the export, ensuring that the inserted rows in the tables will receive the next exact auto-increment ID value.
  • Enclose table and field names with backquotes: In the MySQL world, backquotes are the normal way of protecting table and field names that may contain special characters. In most cases, it's useful to have them. However, backquotes are not recommended if the target server (where the export file will be imported) is running a SQL engine that does not support backquotes.
  • Add CREATE PROCEDURE / FUNCTION / EVENT: This includes all procedures, functions, and event definitions found in this database, in the export.
  • Add into comments: This adds information (in the form of SQL comments), which cannot be directly imported, but which nonetheless is valuable and human-readable table information. The amount of information here varies depending on the relational system settings (see Chapter 10, Benefiting from the Relational System). In fact, with an activated relational system, we would get the following choices:
Defining options for SQL export

Selecting Relations and MIME type would produce an additional section in the structure export:

--
-- COMMENTS FOR TABLE `book`:
-- `isbn`
-- 'book number'
-- `page_count`
-- 'approximate'
-- `author_id`
-- 'see author table'
--
--
-- MIME TYPES FOR TABLE `book`:
-- `cover_photo`
-- 'image_jpeg'
-- `date_released`
-- 'text_plain`
-- `description'
-- 'text_plain'
--
-- RELATIONS FOR TABLE `book`:
-- `author_id`
-- 'author' -> 'id' 
--

The following screenshot displays options relevant to a Data export:

Defining options for SQL export

The options available in the Data section are:

  • Complete inserts: Generates the following export for the author table:
    INSERT INTO `author` (`id`, `name`, `phone`) VALUES (1, 'John Smith', '+01 445 789-1234');
    INSERT INTO `author` (`id`, `name`, `phone`) VALUES (2, 'Maria Sunshine', '+01 455 444-5683');
    

    Notice that every column name is present in every statement. The resulting file is bigger, but will prove more portable on various SQL systems, with the added benefit of being better documented.

  • Extended inserts: Packs the whole table data into a single INSERT statement:
    INSERT INTO `author` VALUES (1, 'John Smith','+01 445 789-1234'), (2, 'Maria Sunshine', '+01 455 444-5683');
    

    This method of inserting data is faster than using multiple INSERT statements, but is less convenient because it makes reading the resultant file harder. Extended inserts also produces a smaller file, but each line of this file is not executable in itself because each line does not have an INSERT statement. If you cannot import the complete file in one operation, you cannot split the file with a text editor and import it chunk by chunk.

  • Maximal length of created query: The single INSERT statement generated for Extended inserts might become too big and could cause problems. Hence, we set a limit on the number of characters for the length of this statement.
  • Use delayed inserts: Adds the DELAYED modifier to INSERT statements. This accelerates the INSERT operation because it's queued to the server, which will execute it when the table is not in use. This is a MySQL non-standard extension, available only for MyISAM, MEMORY, and ARCHIVE tables.
  • Use ignore inserts: Normally, at import time, we cannot insert duplicate values for unique keys, as this would abort the insert operation. This option adds the IGNORE modifier to INSERT and UPDATE statements, thus skipping the rows that generate duplicate key errors.
  • Use hexadecimal for BLOB: This option makes phpMyAdmin encode the contents of BLOB fields in 0x format. Such a format is useful because, depending on the software that will be used to manipulate the export file (for example, a text editor or mail program), handling a file containing 8-bit data can be problematic. However, using this option will produce an export of the BLOB that can be twice the size of a file generated without this option.
  • Export type: The choices are INSERT, UPDATE, and REPLACE. The most well-known of these types is the default INSERT—using INSERT statements to import back our data. At import time, however, we could be in a situation where a table already exists and contains valuable data, and we just want to update the fields that are in the current table we are exporting. UPDATE generates statements such as UPDATE `author` SET `id` = 1, `name` = 'John Smith', `phone` = '111 1111' WHERE `id` = '1'; updating a row when the same primary or unique key is found. The third possibility, REPLACE, produces statements such as REPLACE INTO `author` VALUES (1, 'John Smith', '111-1111');. These act like an INSERT statement for new rows and update existing rows based on primary or unique keys.

The "Save as file" subpanel

In the previous examples, the results of the export operation were displayed on screen and, of course, no compression was made on the data. We can choose to transmit the export file via HTTP by checking the Save as file checkbox. This triggers a Save dialog in the browser, which ultimately saves the file on our local workstation.

The "Save as file" subpanel

File name template

The name of the proposed file will obey the File name template. In this template, we can use the special __SERVER__, __DB__, and __TABLE__ placeholders. These placeholders will be replaced by the current server, database, or table name (for a single-table export). Note that there are two underscore characters before and after the words. We can also use any special character from the PHP strftime function; this is useful for generating an export file based on the current date or hour. Finally, we can put any other string of characters (not part of the strftime special characters), which will be used literally. The file extension is generated according to the type of export. In this case, it will be .sql. Here are some examples for the template:

  • __DB__ would generate marc_book.sql
  • __DB__-%Y%m%d would give marc_book-20071206.sql

The remember template option, when activated, stores the entered template settings into cookies (for database, table, or server exports) and brings them back the next time we use the same kind of export.

The default templates are configurable, via the following parameters:

$cfg['Export']['file_template_table'] = '__TABLE__';
$cfg['Export']['file_template_database'] = '__DB__';
$cfg['Export']['file_template_server'] = '__SERVER__';

Compression

To save transmission time and generate a smaller export file, phpMyAdmin can compress to ZIP, GZIP, or BZIP2 formats. These formats work only if the PHP server has been compiled with the --with-zlib (for ZIP and GZIP) or --with-bz2 (for BZ2) configuration option respectively. The following parameters control which compression choices are presented in the panel:

$cfg['ZipDump'] = TRUE;
$cfg['GZipDump'] = TRUE;
$cfg['BZipDump'] = TRUE;

A system administrator installing phpMyAdmin for a number of users could choose to set all of these parameters to FALSE, so as to avoid the potential overhead incurred by a lot of users compressing their exports at the same time. This situation usually causes more overhead than if all the users were transmitting their uncompressed files at the same time.

In older phpMyAdmin versions, the compression file was built in the web server memory. Some problems caused by this were:

  • File generation depended on the memory limits assigned to running PHP scripts.
  • During the time when the file was being generated and compressed, no transmission occurred. Hence, users were inclined to think that the operation was not working and that something had crashed.
  • Compression of large databases was impossible to achieve.

The $cfg['CompressOnFly'] parameter (set to TRUE by default) was added to generate (for gzip and bzip2 formats) a compressed file containing more headers. Now, the transmission starts almost immediately. The file is sent in smaller chunks so that the whole process consumes much lesser memory. The downside of this is a slightly larger resulting file.

Choosing a character set

This section explains a little-known feature—the possibility of choosing the exact character set for our exported file.

This feature is activated by setting $cfg['AllowAnywhereRecoding'] to TRUE. We can see here the effect on the interface:

Choosing a character set

When this parameter is switched on, phpMyAdmin verifies that the conditions for recoding are met. For the actual encoding of data, the PHP component of the web server must support the iconv or the recode module. If this is not the case and the parameter has been set to TRUE, the following error message will be generated:

Couldn't load the iconv or recode extension needed for charset conversion. Either configure PHP to enable these extensions or disable charset conversion in phpMyAdmin.

If this message is displayed, consult your system's documentation (PHP or the operating system) for the installation procedure.

Another parameter ($cfg['RecodingEngine']) specifies the actual recoding engine—the choices being auto, iconv, and recode. If it's set to auto, phpMyAdmin will first try the iconv module and then the recode module.

Kanji support

If phpMyAdmin detects the use of the Japanese language, it checks whether PHP supports the mb_convert_encoding() multibyte strings function. If it does, additional radio buttons—export, import, and query box—are displayed on the following pages, so that we can choose between the EUC-JP and SJIS Japanese encodings.

Here is an example taken from the Export page:

Kanji support

CSV

The comma-separated value (CSV) format is understood by a lot of programs, and you may find it useful for exchanging data. Note that it's a data-only format—there is no SQL structure here:

CSV

The available options are:

  • Fields terminated by: We put a comma here, which means that a comma will be placed after each field.
  • Fields enclosed by: We place an enclosing character here (like the quote) to ensure that a field containing the terminating character (comma) is not interpreted as two fields.
  • Fields escaped by: If the export generator finds the Fields enclosed by character inside a field, the Fields escaped by character will be placed before it in order to protect it. For example, "John \"The Great\" Smith".
  • Lines terminated by: This decides the character that ends each line. We should use the correct line delimiter here, according to the operating system on which we will manipulate the resulting export file. The default value of this option comes from the $cfg['Export']['csv_terminated'] parameter, which contains'AUTO' by default. The'AUTO' value produces a value of \r\n if the browser's OS is Windows and \n otherwise. However, this might not be the best choice if the export file is intended for a machine with a different OS.
  • Replace NULL by: This determines which string occupies the place in the export file of any NULL value found in a field.
  • Remove CRLF characters within fields: As a column can contain carriage return or line feed characters, this option determines if such characters should be removed from the exported data.
  • Put fields names in the first row: This gets some information about the meaning of each field. Some programs will use this information to name the column.

Finally, we select the author table.

The result is:

"id","name","phone"
"1","John Smith","+01 445 789-1234"
"2","Maria Sunshine","+01 455 444-5683"

CSV for MS Excel

This export mode produces a CSV file specially formatted for Microsoft Excel. We can select the exact Microsoft Excel edition:

CSV for MS Excel

PDF

It's possible to create a PDF report of a table by exporting in PDF. This feature works on only one table at a time, and we must click on the Save as file checkbox for normal operation. We can add a title for this report, and it also gets automatically paginated. Non-textual (BLOB) data, as found in the book table, is discarded from this export format.

Here, we test it on the author table:

PDF

PDF is interesting because of its inherent vectorial nature—the results can be zoomed. Let's have a look at the generated report, as seen in Adobe Reader:

PDF

Microsoft Word 2000

This export format directly produces a .doc file suitable for all software that understands the Word 2000 format. We find options similar to those in the Microsoft Excel export, and a few more. We can independently export the table's Structure and Data.

Microsoft Word 2000

Note that, for this format and the Excel format, we can choose many tables for one export. However, unpleasant results happen if one of these tables has non-textual data. Here are the results for the author table:

Microsoft Word 2000

LaTeX

LaTeX is a typesetting language. phpMyAdmin can generate a .tex file that represents the table's structure and/or data in a sideways tabular format.

LaTeX

Note

Note that this file is not directly viewable, and must be processed further or converted for the intended final media.

The available options are:

Option

Description

Include table caption

Display captions in the tabular output.

Structure and Data

The familiar choice to request structure, data, or both.

Table caption

The caption to appear on the first page.

Continued table caption

The caption to appear on subsequent pages.

Relations, Comments, MIME-type

Other structure information that we want to output. These choices are available if the relational infrastructure is in place (see Chapter 10, Benefiting from the Relational System, for details).

XML

The XML format is very popular these days for data exchange. Choosing XML in the Export interface yields no choice for options. What follows is the output of the author table:

<?xml version="1.0" encoding="utf-8" ?>
<!--
-
- phpMyAdmin XML Dump
- version 3.3.2
- http://www.phpmyadmin.net
-
- Host: localhost
- Generation Time: May 16, 2010 at 09:30 AM
- Server version: 5.1.45
- PHP Version: 5.3.2
-->
<!--
- Database: 'marc_book'
-->
<marc_book>
<!-- Table author -->
<author>
<id>1</id>
<name>John Smith</name>
<phone>+01 445-789-1234</phone>
</author>
<author>
<id>2</id>
<name>Maria Sunshine</name>
<phone>333-3333</phone>
</author>
</marc_book>

Open document spreadsheet

The open document spreadsheet format is a subset of the open document (http://en.wikipedia.org/wiki/OpenDocument), which was made popular with the OpenOffice.org office suite. We need to choose only one table to be exported in order to have a coherent spreadsheet. Here is our author table, exported into a file named author.ods, and subsequently looked at from OpenOffice:

Open document spreadsheet

Open document text

Open document text is another subset of the open document standard, this time oriented towards text processing. The available options are as shown in the following screenshot:

Open document text

Our author table is now exported and appears as follows when viewed in OpenOffice:

Open document text

YAML

YAML stands for YAML Ain't Markup Language. YAML is a human-readable data serialization format; its official site is http://www.yaml.org. This format has no option that we can choose from within phpMyAdmin. Here is the YAML export for the author table:

1:
id: 1
name: John Smith
phone: +01 445-789-1234
2:
id: 2
name: Maria Sunshine
phone: 333-3333

CodeGen

The CodeGen option might some day support many formats related to code development. Currently, it can export in NHibernate Object-relation mapping (ORM) format. For more details, please refer to http://en.wikipedia.org/wiki/Nhibernate.

Texy! text

Texy! is a formatting tool (http://texy.info/en/) with its own simplified syntax. Here is an example of export in Texy! format:

===Database marc_book
== Table structure for table author
|------
|Field|Type|Null|Default
|------
|//**id**//|int(11)|Yes|NULL
|name|varchar(30)|Yes|NULL
|phone|varchar(30)|Yes|NULL
== Dumping data for table author
|1|John Smith|+01 445 789-1234
|2|Maria Sunshine|333-3333

PHP array

In PHP, associative arrays can hold text data; therefore, a PHP array export format is available. It produces a file containing, for example:

<?php
// marc_book.author
$author = array(
array('id'=>1,'name'=>'John Smith','phone'=>'+1 445 789-1234'),
array('id'=>2,'name'=>'Maria Sunshine','phone'=>'333-3333')
);

Excel 97-2003 and Excel 2007 Workbook

Thanks to the PHPExcel library (http://www.codeplex.com/PHPExcel), which is included in phpMyAdmin, it's possible to produce a native Excel 97-2003 or Excel 2007 export file. For this to work, we need a work directory under the main phpMyAdmin directory. This work directory can be created on a Linux system with mkdir tmp ; chmod o+rwx tmp. We also need to set the $cfg['TempDir'] parameter in config.inc.php to'./tmp'.

Note

On a shared host, having such an unprotected directory is dangerous as it possibly provides write access to other users of this server.

This export format directly produces a .xls or .xlsx file suitable for all software that understands these formats. We can specify which string should replace a NULL value. The Put fields names in the first row option, when activated, generates the table's column names as the first line of the spreadsheet. Again, the Save as file checkbox should be checked. This produces a file where each table's column becomes a spreadsheet column:

Excel 97-2003 and Excel 2007 Workbook

MediaWiki table

MediaWiki (http://www.mediawiki.org/wiki/MediaWiki) is a popular wiki package which supports the ubiquitous Wikipedia. This wiki software implements a formatting language in which it's possible to describe data in tabular format. Choosing this export format in phpMyAdmin produces a file that can be pasted in a wiki page that we are editing.