mysql_real_escape_string()
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 function 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 twice the size of the source string, plus one byte. Here is an example:
...
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 twice 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 the C function sprintf(), the escaped
client name is inserted into the SQL statement given. Finally, the SQL
statement is run with
mysql_real_query().