Name
mysql_escape_string( )
Synopsis
unsigned int mysql_escape_string(char *destination, const char *source, const char *source, unsigned int length)
This
returns a string given as the second argument 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 third. When
declaring the two strings, the destination must be double the source
string, plus one byte. This function does not include a
MYSQL
object (which includes knowledge of the
current character set), so it may not be comprehensive. This is a
security problem. Use the mysql_real_escape_string()
function instead, which does this job properly and
safely.
... char client_name[ ] = "O'Reilly Media"; unsigned int bytes = strlen(client_name); char client_name_esc[(2 * bytes) + 1]; mysql_escape_string(client_name_esc, client_name, bytes); char *sql_stmnt; sprintf(sql_stmnt, "INSERT INTO clients (client_name) VALUES('%s')", client_name_esc); printf("SQL Statement:\n%s", sql_stmnt); mysql = mysql_init(NULL); mysql_real_connect(mysql,host,user,password,database, port,socket,flag); mysql_real_query(mysql, sql_stmnt, strlen(sql_stmnt)); ...
In this example, the client name is first stored in the
client_name
variable. Next, the number of bytes
contained in the variable is calculated with the C function
strlen( )
and stored in the bytes
variable. Then the client_name_esc
variable is declared with a size of the value contained in
bytes
doubled, plus one, ...
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.