Home > Articles > Data > MySQL

  • Print
  • + Share This
This chapter is from the book

This chapter is from the book

Miscellaneous Topics

This section covers several subjects that didn't fit very well into the progression as we went from client1 to client5:

  • Using 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 that are troublesome to insert into queries.

  • How to work with image 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 row data, but clearly there will be times when you need to do something with your data 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).

  • The column must contain numeric values.

If these conditions do not hold, summary_stats() simply prints an error message and returns. The code is 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 */
  if (mysql_num_fields (res_set) < col_num)
    print_error (NULL, "illegal column number");
  mysql_field_seek (res_set, 0);
  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's there to allow you to call summary_stats() multiple times for the same result set (in case you want to calculate statistics on several columns). Each time summary_stats() is invoked, it "rewinds" to the beginning of the result set. (This assumes 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.

Encoding Problematic Data in Queries

Data values containing quotes, nulls, or backslashes, if inserted literally into a query, 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 name:

char query[1024];

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

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

SELECT * FROM my_tbl 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. One way to do this is to double the quote within the string. That is the ANSI SQL convention. MySQL understands that convention, and also allows the quote to be preceded by a backslash:

SELECT * FROM my_tbl WHERE name='O''Malley, Brian' 
SELECT * FROM my_tbl 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 may contain any character, it cannot be considered safe to put into a query as is.

To deal with this problem, use mysql_escape_string(), which encodes special characters to make them usable in quoted strings. Characters that mysql_escape_string() considers special are the null character, single quote, double quote, backslash, newline, carriage return, and Control-Z. (The last one occurs in Windows contexts.)

When should you use mysql_escape_string()? The safest answer is "always." However, if you're sure of the form 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_escape_string(). Otherwise, you probably should.

mysql_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_escape_string(), invoke it like this:

to_len = mysql_escape_string (to_str, from_str, from_len);

mysql_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() and strlen().

from_str points to a char buffer containing the string to be encoded. This string may 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_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 2 characters; the extra byte is for the terminating null.)

from_len and to_len are unsigned int 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_escape_string(), is the actual length of the resulting encoded string, not counting the terminating null.

When mysql_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 values of names that contain quotes, we could do something like this:

char query[1024], *p;

p = strcpy (query, "SELECT * FROM my_tbl WHERE name='");
p += strlen (p);
p += mysql_escape_string (p, name, strlen (name));
p = strcpy (p, "'");

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

char query[1024], buf[1024];

(void) mysql_escape_string (buf, name, strlen (name));
sprintf (query, "SELECT * FROM my_tbl WHERE name='%s'", buf);

Working With Image Data

One of the jobs for which mysql_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, along with a unique identifier. The BLOB type is a good choice for binary data, so you could use a table specification like this:

  image_data BLOB

To actually get an image from a file into the images 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 int  from_len;
int       status;

  sprintf (query, "INSERT INTO images VALUES (%d,'", id);
  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_escape_string (p, buf, from_len);
  (void) strcpy (p, "')");
  status = mysql_query (conn, query);
  return (status);

load_image() doesn't allocate a very large query buffer (100K), 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.

Handling image data (or any binary data) that you get back out of a database isn't nearly as much of a problem as putting it in to begin with because the data values are available in raw form in the MYSQL_ROW variable, and the lengths are available by calling mysql_fetch_lengths(). Just be sure to treat the values as counted strings, not as null-terminated strings.

Getting Table Information

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

DESCRIBE tbl_name

Both statements are like SELECT in that they return 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 images statement from the mysql client, it returns this information:

| Field      |   Type  | Null | Key | Default | Extra |
| image_id   | int(11) |      | PRI | 0       |       |
| image_data | blob    | YES  |     | NULL    |       |

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

If you want information only about a single column, use this query instead:

SHOW FIELDS FROM tbl_name LIKE "col_name"

The query will return the same columns, but only one row (or no rows if the column doesn't exist).

Client Programming Mistakes To Avoid

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

Mistake 1—Using Uninitialized Connection Handler Pointers

In the examples shown in this chapter, we've called mysql_init() by passing a NULL argument to it. This 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 problems. The following discussion points out some problems to watch out for.

If you pass a pointer to mysql_init(), it should actually point to something. Consider this 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, NULL) before the program starts up. mysql_init() sees a NULL argument, so it initializes and allocates a new connection handler. Unfortunately, conn is still 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.

Mistake 2—Failing to Test for a Valid Result Set

Remember to check the status of calls from which you expect to get a result set. This 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, and the while loop shouldn't even be executed. Test the return value of functions that return result sets to make sure you actually have something to work with.

Mistake 3—Failing to Account for NULL Column Values

Don't forget to check whether or not 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 crashes and your friend concludes you're a lousy programmer. The loop should be written like this 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 or not 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. This code violates that principle:

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

len = mysql_escape_string (to_str, from_str, strlen (from_str));

What's the problem? to_str must point to an existing buffer. In this example, it doesn't—it points to some random location. Don't pass an uninitialized pointer as the to_str argument to mysql_escape_string() unless you want it to stomp merrily all over some random piece of memory.

  • + Share This
  • 🔖 Save To Your Account

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information

To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.


Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.


If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information

Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.


This site is not directed to children under the age of 13.


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information

If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information

Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents

California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure

Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact

Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice

We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020