mysql_escape_string escape a mysql string
” will be escaped
; will not be escaped
! mysql_escape_string is outdated use mysql_real_escape_string instead !
#include <stdio.h> /* including standard library */ #include <mysql/mysql.h> MYSQL *my; MYSQL_RES *result; int main( void ){ char host[20]; char user[20]; char pass[20]; // variables for escape char from[90]; char query[90]; char to[90]; unsigned int length = 0; my = mysql_init(NULL); sprintf(host,"localhost"); sprintf(user,"username"); sprintf(pass,"password"); if (my == NULL ) { printf("Cant initalisize MySQL\n"); return 1; } if( mysql_real_connect (my,host,user,pass,NULL,0,NULL,0) == NULL) { printf("Error cant login\n"); } else { printf("Login correct\n"); } mysql_select_db(my, "test"); // e.g. what the user send ... in this case a SQL injection sprintf(from, "user1 ; SELECT * FROM usertable WHERE userid = \"user2\""); length = strlen(from); mysql_escape_string(to, from, length); // new escaped string sprintf(query, "SELECT id FROM usertable WHERE user_id = \"%s\"; ",to); printf("%s\n",query); mysql_close(my); return 0; }
Login correct SELECT id FROM usertable WHERE user_id = "user1 ; SELECT * FROM usertable WHERE userid = \"user2\"";