MariaDB Cookbook
上QQ阅读APP看书,第一时间看更新

Producing HTML output

The mysql command-line client has several different output options. One of these is HTML.

Getting ready

Import the ISFDB database as described in the Importing the data exported by mysqldump recipe in this chapter. Create a file called isfdb-001.sql using the following command line:

SELECT * FROM authors LIMIT 100;

We could put whatever commands we want in this file, or give it a different name, but this works for the purposes of this recipe.

How to do it...

  1. Open a terminal and navigate to where we saved the isfdb-001.sql file.
  2. Issue the following command on the command line (not from within the mysql command-line client, but by calling the client with some special options):
    mysql --html isfdb < isfdb-001.sql > isfdb-001.html
    
  3. Execute either a dir or ls command and we'll see that now there is a file named isfdb-001.html in the directory.
  4. We can now either open the newly created isfdb-001.html file in our favorite text editor, or view it in a web browser, such as Firefox, Chrome, or Opera.

How it works...

When the --html flag is passed on the command line, the mysql command-line client will spit out an HTML table instead of a regular output; no headers, footers, or DOCTYPE, just a table with the results as one long string.

On the command line, we use the < and > redirectors to read in the isfdb-001.sql file and then to direct the output to the isfdb-001.html file, respectively.

There's more...

The HTML output that the mysql command-line client produces is not pretty. What's more, it's not a completely valid HTML file as there's no DOCTYPE, no <head> section, no <body> section, no <title>, and so on. The file we created begins with a <TABLE> tag and ends with a closing </TABLE> tag. And yes, all the tags use the old uppercase style of writing HTML code.

In Linux, there is an easy way to remedy this using the Tidy program. If it is not already installed, it is easy to do so using our package manager. To clean up our HTML, add spaces and indentation, change the case of the tags to lowercase, and add a DOCTYPE and all the necessary sections. We will simply modify our recipe to the following command line:

mysql --html isfdb < isfdb-001.sql | tidy -q -i -o isfdb-001.html

Tidy will detect the appropriate DOCTYPE, change the case of the tags, indent the code, and add in the missing sections.

Of course, even tidied up, HTML output is of limited use. It is, however, something the mysql command-line client can do.

See also