Miscellaneous Topics

This section covers several query-processing subjects that didn't fit very well into earlier sections of this chapter:

  • How to use result set data to calculate a result after using result set metadata to help verify that the data are suitable for your calculations

  • How to deal with data values that are troublesome to insert into queries

  • How to work with binary data

  • How to get information about the structure of your tables

  • Common MySQL programming mistakes and how to avoid them

Performing Calculations on Result Sets

So far we've concentrated on using result set metadata primarily for printing query rows, but clearly there will be times when you need to do something with a result set besides print it. For example, you can compute statistical information based on the data values, using the metadata to make sure the data conform to requirements you want them to satisfy. What type of requirements? For starters, you'd probably want to verify that a column on which you're planning to perform numeric computations actually contains numbers.

The following listing shows a simple function, summary_stats(), that takes a result set and a column index and produces summary statistics for the values in the column. The function also reports the number of missing values, which it detects by checking for NULL values. These calculations involve two requirements that the data must satisfy, so summary_stats() verifies them using the result set metadata:

  • The specified column must exist?that is, the column index must be within range of the number of columns in the result set. This range is from 0 to mysql_num_fields()?1.

  • The column must contain numeric values.

If these conditions do not hold, summary_stats() simply prints an error message and returns. It is implemented as follows:

summary_stats (MYSQL_RES *res_set, unsigned int col_num)
MYSQL_FIELD     *field;
MYSQL_ROW       row;
unsigned int    n, missing;
double          val, sum, sum_squares, var;

    /* verify data requirements: column must be in range and numeric */
    if (col_num < 0 || col_num >= mysql_num_fields (res_set))
        print_error (NULL, "illegal column number");
    mysql_field_seek (res_set, col_num);
    field = mysql_fetch_field (res_set);
    if (!IS_NUM (field->type))
        print_error (NULL, "column is not numeric");

    /* calculate summary statistics */

    n = 0;
    missing = 0;
    sum = 0;
    sum_squares = 0;

    mysql_data_seek (res_set, 0);
    while ((row = mysql_fetch_row (res_set)) != NULL)
        if (row[col_num] == NULL)
            val = atof (row[col_num]);  /* convert string to number */
            sum += val;
            sum_squares += val * val;
    if (n == 0)
        printf ("No observations\n");
        printf ("Number of observations: %lu\n", n);
        printf ("Missing observations: %lu\n", missing);
        printf ("Sum: %g\n", sum);
        printf ("Mean: %g\n", sum / n);
        printf ("Sum of squares: %g\n", sum_squares);
        var = ((n * sum_squares) - (sum * sum)) / (n * (n - 1));
        printf ("Variance: %g\n", var);
        printf ("Standard deviation: %g\n", sqrt (var));

Note the call to mysql_data_seek() that precedes the mysql_fetch_row() loop. It positions to the first row of the result set, which is useful in case you want to call summary_stats() multiple times for the same result set (for example, to calculate statistics on several different columns). The effect is that each time summary_stats() is invoked, it "rewinds" to the beginning of the result set. The use of mysql_data_seek() requires that you create the result set with mysql_store_result(). If you create it with mysql_use_result(), you can only process rows in order, and you can process them only once.

summary_stats() is a relatively simple function, but it should give you an idea of how you could program more complex calculations, such as a least-squares regression on two columns or standard statistics such as a t-test or an analysis of variance.

Encoding Problematic Data in Queries

If inserted literally into a query, data values containing quotes, nulls, or backslashes can cause problems when you try to execute the query. The following discussion describes the nature of the difficulty and how to solve it.

Suppose you want to construct a SELECT query based on the contents of the null-terminated string pointed to by the name_val variable:

char query[1024]; 

sprintf (query, "SELECT * FROM mytbl WHERE name='%s'", name_val);

If the value of name_val is something like O'Malley, Brian, the resulting query is illegal because a quote appears inside a quoted string:

SELECT * FROM mytbl WHERE name='O'Malley, Brian' 

You need to treat the quote specially so that the server doesn't interpret it as the end of the name. The ANSI SQL convention for doing this is to double the quote within the string. MySQL understands that convention and also allows the quote to be preceded by a backslash, so you can write the query using either of the following formats:

SELECT * FROM mytbl WHERE name='O''Malley, Brian' 
SELECT * FROM mytbl WHERE name='O\'Malley, Brian'

Another problematic situation involves the use of arbitrary binary data in a query. This happens, for example, in applications that store images in a database. Because a binary value can contain any character (including quotes or backslashes), it cannot be considered safe to put into a query as is.

To deal with this problem, use mysql_real_escape_string(), which encodes special characters to make them usable in quoted strings. Characters that mysql_real_escape_string() considers special are the null character, single quote, double quote, backslash, newline, carriage return, and Ctrl-Z. (The last one is special on Windows, where it often signifies end-of-file.)

When should you use mysql_real_escape_string()? The safest answer is "always." However, if you're sure of the format of your data and know that it's okay?perhaps because you have performed some prior validation check on it?you need not encode it. For example, if you are working with strings that you know represent legal phone numbers consisting entirely of digits and dashes, you don't need to call mysql_real_escape_string(). Otherwise, you probably should.

mysql_real_escape_string() encodes problematic characters by turning them into 2-character sequences that begin with a backslash. For example, a null byte becomes '\0', where the '0' is a printable ASCII zero, not a null. Backslash, single quote, and double quote become '\\', '\'', and '\"'.

To use mysql_real_escape_string(), invoke it as follows:

to_len = mysql_real_escape_string (conn, to_str, from_str, from_len); 

mysql_real_escape_string() encodes from_str and writes the result into to_str. It also adds a terminating null, which is convenient because you can use the resulting string with functions such as strcpy(), strlen(), or printf().

from_str points to a char buffer containing the string to be encoded. This string can contain anything, including binary data. to_str points to an existing char buffer where you want the encoded string to be written; do not pass an uninitialized or NULL pointer, expecting mysql_real_escape_string() to allocate space for you. The length of the buffer pointed to by to_str must be at least (from_len*2)+1 bytes long. (It's possible that every character in from_str will need encoding with two characters; the extra byte is for the terminating null.)

from_len and to_len are unsigned long values. from_len indicates the length of the data in from_str; it's necessary to provide the length because from_str may contain null bytes and cannot be treated as a null-terminated string. to_len, the return value from mysql_real_escape_string(), is the actual length of the resulting encoded string, not counting the terminating null.

When mysql_real_escape_string() returns, the encoded result in to_str can be treated as a null-terminated string because any nulls in from_str are encoded as the printable '\0' sequence.

To rewrite the SELECT-constructing code so that it works even for name values that contain quotes, we could do something like the following:

char query[1024], *p; 

p = strcpy (query, "SELECT * FROM mytbl WHERE name='");
p += strlen (p);
p += mysql_real_escape_string (conn, p, name, strlen (name));
*p++ = '\'';
*p = '\0';

Yes, that's ugly. If you want to simplify the code a bit, at the cost of using a second buffer, do the following instead:

char query[1024], buf[1024]; 

(void) mysql_real_escape_string (conn, buf, name, strlen (name));
sprintf (query, "SELECT * FROM mytbl WHERE name='%s'", buf);

mysql_real_escape_string() is unavailable prior to MySQL 3.23.14. As a workaround, you can use mysql_escape_string() instead:

to_len = mysql_escape_string (to_str, from_str, from_len); 

The difference between them is that mysql_real_escape_string() uses the character set for the current connection to perform encoding. mysql_escape_string() uses the default character set (which is why it doesn't take a connection handler argument). To write source that will compile under any version of MySQL, include the following code fragment in your file:

#if !defined(MYSQL_VERSION_ID) || (MYSQL_VERSION_ID<32314) 
#define mysql_real_escape_string(conn,to_str,from_str,len) \

Then write your code in terms of mysql_real_escape_string(); if that function is unavailable, the #define causes it to be mapped to mysql_escape_string() instead.

Working with Image Data

One of the jobs for which mysql_real_escape_string() is essential involves loading image data into a table. This section shows how to do it. (The discussion applies to any other form of binary data as well.)

Suppose you want to read images from files and store them in a table named picture along with a unique identifier. The BLOB type is a good choice for binary data, so you could use a table specification like this:

    pict_id     INT NOT NULL PRIMARY KEY,
    pict_data   BLOB

To actually get an image from a file into the picture table, the following function, load_image(), does the job, given an identifier number and a pointer to an open file containing the image data:

load_image (MYSQL *conn, int id, FILE *f)
char            query[1024*100], buf[1024*10], *p;
unsigned long   from_len;
int             status;

    sprintf (query,
            "INSERT INTO picture (pict_id,pict_data) VALUES (%d,'",
    p = query + strlen (query);
    while ((from_len = fread (buf, 1, sizeof (buf), f)) > 0)
        /* don't overrun end of query buffer! */
        if (p + (2*from_len) + 3 > query + sizeof (query))
            print_error (NULL, "image too big");
            return (1);
        p += mysql_real_escape_string (conn, p, buf, from_len);
    *p++ = '\'';
    *p++ = ')';
    status = mysql_real_query (conn, query, (unsigned long) (p - query));
    return (status);

load_image() doesn't allocate a very large query buffer (100KB), so it works only for relatively small images. In a real-world application, you might allocate the buffer dynamically based on the size of the image file.

Getting an image value (or any binary value) back out of a database isn't nearly as much of a problem as putting it in to begin with because the data value is available in raw form in the MYSQL_ROW variable, and the length is available by calling mysql_fetch_lengths(). Just be sure to treat the value as a counted string, not as a null-terminated string.

Getting Table Information

MySQL allows you to get information about the structure of your tables, using any of the following queries (which are equivalent):

DESCRIBE tbl_name;
EXPLAIN tbl_name;

Each statement is like SELECT in that it returns a result set. To find out about the columns in the table, all you need to do is process the rows in the result to pull out the information you want. For example, if you issue a DESCRIBE president statement using the mysql client, it returns the following information:

mysql> DESCRIBE president; 
| Field      | Type        | Null | Key | Default    | Extra |
| last_name  | varchar(15) |      |     |            |       |
| first_name | varchar(15) |      |     |            |       |
| suffix     | varchar(5)  | YES  |     | NULL       |       |
| city       | varchar(20) |      |     |            |       |
| state      | char(2)     |      |     |            |       |
| birth      | date        |      |     | 0000-00-00 |       |
| death      | date        | YES  |     | NULL       |       |

If you execute the same query from your own client program, you get the same information (without the boxes).

If you want information only about a single column, add the column name:

mysql> DESCRIBE president birth; 
| Field | Type | Null | Key | Default    | Extra |
| birth | date |      |     | 0000-00-00 |       |

Client Programming Mistakes to Avoid

This section discusses some common MySQL C API programming errors and how to avoid them. (These problems crop up periodically on the MySQL mailing list; I'm not making them up.)

Mistake 1?Using Uninitialized Connection Handler Pointers

The examples shown earlier in this chapter invoke mysql_init() with a NULL argument. That tells mysql_init() to allocate and initialize a MYSQL structure and return a pointer to it. Another approach is to pass a pointer to an existing MYSQL structure. In this case, mysql_init() will initialize that structure and return a pointer to it without allocating the structure itself. If you want to use this second approach, be aware that it can lead to certain subtle difficulties. The following discussion points out some problems to watch out for.

If you pass a pointer to mysql_init(), it must actually point to something. Consider the following piece of code:

main () 
MYSQL    *conn;

    mysql_init (conn);

The problem is that mysql_init() receives a pointer, but that pointer doesn't point anywhere sensible. conn is a local variable and thus is uninitialized storage that can point anywhere when main() begins execution. That means mysql_init() will use the pointer and scribble on some random area of memory. If you're lucky, conn will point outside your program's address space and the system will terminate it immediately so that you'll realize that the problem occurs early in your code. If you're not so lucky, conn will point into some data that you don't use until later in your program, and you won't notice a problem until your program actually tries to use that data. In that case, your problem will appear to occur much farther into the execution of your program than where it actually originates and may be much more difficult to track down.

Here's a similar piece of problematic code:

MYSQL    *conn; 

main ()
    mysql_init (conn);
    mysql_real_connect (conn, ...)
    mysql_query(conn, "SHOW DATABASES");

In this case, conn is a global variable, so it's initialized to 0 (that is, to NULL) before the program starts up. mysql_init() sees a NULL argument, so it initializes and allocates a new connection handler. Unfortunately, the value of conn remains NULL because no value is ever assigned to it. As soon as you pass conn to a MySQL C API function that requires a non-NULL connection handler, your program will crash. The fix for both pieces of code is to make sure conn has a sensible value. For example, you can initialize it to the address of an already-allocated MYSQL structure:

MYSQL conn_struct, *conn = &conn_struct; 
mysql_init (conn);

However, the recommended (and easier!) solution is simply to pass NULL explicitly to mysql_init(), let that function allocate the MYSQL structure for you, and assign conn the return value:

MYSQL *conn; 
conn = mysql_init (NULL);

In any case, don't forget to test the return value of mysql_init() to make sure it's not NULL (see Mistake 2).

Mistake 2?Failing to Check Return Values

Remember to check the status of calls that may fail. The following code doesn't do that:

MYSQL_RES *res_set; 
res_set = mysql_store_result (conn);
while ((row = mysql_fetch_row (res_set)) != NULL)
    /* process row */

Unfortunately, if mysql_store_result() fails, res_set is NULL, in which case the while loop should never even be executed. (Passing NULL to mysql_fetch_row() likely will crash the program.) Test the return value of functions that return result sets to make sure you actually have something to work with.

The same principle applies to any function that may fail. When the code following a function depends on the success of the function, test its return value and take appropriate action if failure occurs. If you assume success, problems will occur.

Mistake 3?Failing to Account for NULL Column Values

Don't forget to check whether column values in the MYSQL_ROW array returned by mysql_fetch_row() are NULL pointers. The following code crashes on some machines if row[i] is NULL:

for (i = 0; i < mysql_num_fields (res_set); i++) 
    if (i > 0)
        fputc ('\t', stdout);
    printf ("%s", row[i]);
fputc ('\n', stdout);

The worst part about this mistake is that some versions of printf() are forgiving and print "(null)" for NULL pointers, which allows you to get away with not fixing the problem. If you give your program to a friend who has a less-forgiving printf(), the program will crash and your friend will conclude that you're a lousy programmer. The loop should be written as follows instead:

for (i = 0; i < mysql_num_fields (res_set); i++) 
    if (i > 0)
        fputc ('\t', stdout);
    printf ("%s", row[i] != NULL ? row[i] : "NULL");
fputc ('\n', stdout);

The only time you need not check whether a column value is NULL is when you have already determined from the column's information structure that IS_NOT_NULL() is true.

Mistake 4?Passing Nonsensical Result Buffers

Client library functions that expect you to supply buffers generally want them to really exist. Consider the following example, which violates that principle:

char *from_str = "some string"; 
char *to_str;
unsigned long len;

len = mysql_real_escape_string (conn, to_str, from_str, strlen (from_str));

What's the problem? to_str must point to an existing buffer, and it doesn't?it's not initialized and may point to some random location. Don't pass an uninitialized pointer as the to_str argument to mysql_real_escape_string() unless you want it to stomp merrily all over some random piece of memory.