Using C for CGI Programming

You can speed up complex Web tasks while retaining the simplicity of CGI. With many useful libraries available, the jump from a scripting language to C isn't as big as you might think.

Finally, I need a way to handle the submit buttons. They're the most complex input, because I need to launch a function based on their values and select a default value, just in case. The cgic library has a function, cgiFormSelectSingle(), that emulates this behavior exactly. It requires the list of possible values to be in an array of strings. It populates an integer variable with the index of the parameter in the array or uses a default value if there are no matches.

See Resources for information on function pointers. If function pointers still baffle you, you can choose the function to run in a switch statement. I prefer the array of function pointers because it is more compact, but my older code still makes use of the switch statement.

Database System

MySQL from C is largely the same as PHP, if you're used to that interface. You have to use MySQL's string escape functions to escape problematic characters in your strings, such as quote characters or the back slash character, but otherwise it is basically the same. The show_event() function requires me to fetch a single record from the primary key. All of the error checking bulks up the code, but it's really three basic statements. A call to mysql_query() executes the MySQL statement and generates a result set. A call to mysql_store_result() retrieves the result set from the server. Finally, a call to mysql_fetch_row() pulls a single MYSQL_ROW variable from the result set.

The MYSQL_ROW variable can be treated like an array of strings (char**). If any of the data is numeric and you want to treat it as numeric data, you need to convert it. For instance, in my application it is desirable to have the date as three separate numeric components. Because this data is structured as YYYY-MM-DD, I use sscanf() to get the components (Listing 6).

Writing data to the database is more interesting because of the need to escape the data. Listing 7 shows how it is done.

escapedname holds the same string as name, with MySQL special characters escaped so I can insert them into an SQL statement without worry. It is essential that you escape all strings read from user input; otherwise, a devious person could take advantage of your lapse and do unpleasant things to your database.



Comment viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.

source code url broken

Anonymous's picture

Thanks for you cool post. I'm trying to develop rest service by c/cgi, could you fix the broken url and make your source code and makefile available?