set automodes on connect
[NeonServV5.git] / mysqlConn.c
index 2dbd608bef84fb281bac9f80e17e2e3ef6b411ba..81fa038cbbc3af2086ea15e5f11d4c121b005cc8 100644 (file)
@@ -6,12 +6,14 @@ struct used_result {
     struct used_result *next;
 };
 
-static MYSQL *mysql_conn = NULL;
-static struct used_result *used_results;
+struct escaped_string {
+    char *string;
+    struct escaped_string *next;
+};
 
-MYSQL *getMySQL() {
-    return mysql_conn;
-}
+MYSQL *mysql_conn = NULL;
+static struct used_result *used_results;
+static struct escaped_string *escaped_strings;
 
 void check_mysql() {
     if(mysql_ping(mysql_conn)) {
@@ -20,7 +22,7 @@ void check_mysql() {
 }
 
 MYSQL_RES *mysql_use() {
-    MYSQL_RES *res = mysql_use_result(mysql_conn);
+    MYSQL_RES *res = mysql_store_result(mysql_conn);
     struct used_result *result = malloc(sizeof(*result));
     if (!result) {
         mysql_free_result(res);
@@ -33,18 +35,27 @@ MYSQL_RES *mysql_use() {
 }
 
 void mysql_free() {
-    struct used_result *result, *next;
-    for(result = used_results; result; result = next) {
-        next = result->next;
+    struct used_result *result, *next_result;
+    for(result = used_results; result; result = next_result) {
+        next_result = result->next;
         mysql_free_result(result->result);
         free(result);
     }
+    used_results = NULL;
+    struct escaped_string *escaped, *next_escaped;
+    for(escaped = escaped_strings; escaped; escaped = next_escaped) {
+        next_escaped = escaped->next;
+        free(escaped->string);
+        free(escaped);
+    }
+    escaped_strings = NULL;
 }
 
 void init_mysql() {
     mysql_conn = mysql_init(NULL);
     if (!mysql_real_connect(mysql_conn, MYSQL_HOST, MYSQL_USER, MYSQL_PASS, MYSQL_BASE, MYSQL_PORT, NULL, 0)) {
         //error
+        show_mysql_error();
     }
 }
 
@@ -52,3 +63,36 @@ void free_mysql() {
     mysql_close(mysql_conn);
 }
 
+void show_mysql_error() {
+    //show mysql_error()
+    printf("MySQL Error: %s\n", mysql_error(mysql_conn));
+}
+
+void printf_mysql_query(const char *text, ...) {
+    va_list arg_list;
+    char queryBuf[MYSQLMAXLEN];
+    int pos;
+    queryBuf[0] = '\0';
+    va_start(arg_list, text);
+    pos = vsnprintf(queryBuf, MYSQLMAXLEN - 2, text, arg_list);
+    va_end(arg_list);
+    if (pos < 0 || pos > (MYSQLMAXLEN - 2)) pos = MYSQLMAXLEN - 2;
+    queryBuf[pos] = '\0';
+    printf("MySQL: %s\n", queryBuf);
+    if(mysql_query(mysql_conn, queryBuf)) {
+        show_mysql_error();
+    }
+}
+
+char* escape_string(const char *str) {
+    struct escaped_string *escapedstr = malloc(sizeof(*escapedstr));
+    if (!escapedstr) {
+        return NULL;
+    }
+    char escaped[strlen(str)*2+1];
+    mysql_real_escape_string(mysql_conn, escaped, str, strlen(str));
+    escapedstr->string = strdup(escaped);
+    escapedstr->next = escaped_strings;
+    escaped_strings = escapedstr;
+    return escapedstr->string;
+}