Name

mysql_real_escape_string( )

Synopsis

unsigned long mysql_real_escape_string(MYSQL *mysql, 
                                       char *result_string, 
                                       char *result_string, 
                                       char *original_string, 
                                       char *result_string, 
                                       char *original_string, 
                                       unsigned long src length)

This writes a string given as the third argument, to a string named in the second argument, but with special characters escaped by adding backslashes in front of them. The number of bytes to be copied from the source string is given for the fourth argument. When declaring the two strings, the destination string must be double the size of the source string, plus one byte.

...
const char client_name[  ] = "O'Reilly Media";
ulong bytes = strlen(client_name);
char client_name_esc[(2 * bytes)+1];
mysql_real_escape_string(mysql, client_name_esc,
                         client_name, bytes);
char *sql_stmnt;
sprintf(sql_stmnt, "INSERT INTO clients (client_name)
                    VALUES('%s')", client_name_esc);
mysql_real_query(mysql, sql_stmnt, strlen(sql_stmnt));
...

After establishing the initial variable for storing the client’s name, the C function strlen( ) is used to determine the number of bytes contained in the string. Next the second variable to hold the client’s name is declared with a size double the size of the first variable, plus one byte. The mysql_real_escape_string( ) function is run with both variables and the size of the first. In this example, the function will place a backslash in front of the apostrophe in the client’s name so as not to cause an error when the query is run later. Using ...

Get MySQL in a Nutshell now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.