20.4.13 mysql_escape_string()

unsigned int mysql_escape_string(char *to, const char *from, unsigned int length)

20.4.13.1 Description

Encodes the string in from to an escaped SQL string that can be sent to the server in a SQL statement, and places the result in to. Characters encoded are NUL (ASCII 0), `\n', `\r', `\' and `'' ( 7.1 Syntaxe des chaînes et nombres).

The string pointed to by from must be length bytes long (not including the terminating null byte). You must allocate the to buffer to be at least length*2+1 bytes long. When mysql_escape_string() returns, the contents of to will be a null-terminated string. The return value is the length of the encoded string, not including the terminating null character.

20.4.13.2 Example

char query[1000],*end;

end = strmov(query,"INSERT INTO test_table values(");
*end++ = '\'';
end += mysql_escape_string(end,"What's this",11);
*end++ = '\'';
*end++ = ',';
*end++ = '\'';
end += mysql_escape_string(end,"binary data: \0\r\n",16);
*end++ = '\'';
*end++ = ')';

if (mysql_real_query(&mysql,query,(unsigned int) (end - query)))
{
   fprintf(stderr, "Failed to insert row, Error: %s\n",
           mysql_error(&mysql));
}

The strmov() function used in the example is included in the mysqlclient library and works like strcpy() but returns a pointer to the terminating null of the first parameter.

20.4.13.3 Return values

The length of the value placed into to, not including the terminating null character.

20.4.13.4 Errors

None.