added some code & compiler information to cmd_netinfo
[NeonServV5.git] / mysqlConn.c
1
2 #include "mysqlConn.h"
3
4 struct used_result {
5     MYSQL_RES *result;
6     struct used_result *next;
7 };
8
9 struct escaped_string {
10     char *string;
11     struct escaped_string *next;
12 };
13
14 MYSQL *mysql_conn = NULL;
15 static struct used_result *used_results;
16 static struct escaped_string *escaped_strings;
17
18 void check_mysql() {
19     if(mysql_ping(mysql_conn)) {
20         //mysql error
21     }
22 }
23
24 MYSQL_RES *mysql_use() {
25     MYSQL_RES *res = mysql_store_result(mysql_conn);
26     struct used_result *result = malloc(sizeof(*result));
27     if (!result) {
28         mysql_free_result(res);
29         return NULL;
30     }
31     result->result = res;
32     result->next = used_results;
33     used_results = result;
34     return res;
35 }
36
37 void mysql_free() {
38     struct used_result *result, *next_result;
39     for(result = used_results; result; result = next_result) {
40         next_result = result->next;
41         mysql_free_result(result->result);
42         free(result);
43     }
44     used_results = NULL;
45     struct escaped_string *escaped, *next_escaped;
46     for(escaped = escaped_strings; escaped; escaped = next_escaped) {
47         next_escaped = escaped->next;
48         free(escaped->string);
49         free(escaped);
50     }
51     escaped_strings = NULL;
52 }
53
54 void init_mysql() {
55     mysql_conn = mysql_init(NULL);
56     if (!mysql_real_connect(mysql_conn, MYSQL_HOST, MYSQL_USER, MYSQL_PASS, MYSQL_BASE, MYSQL_PORT, NULL, 0)) {
57         //error
58         show_mysql_error();
59     }
60 }
61
62 void free_mysql() {
63     mysql_close(mysql_conn);
64 }
65
66 void show_mysql_error() {
67     //show mysql_error()
68     printf("MySQL Error: %s\n", mysql_error(mysql_conn));
69 }
70
71 void printf_mysql_query(const char *text, ...) {
72     va_list arg_list;
73     char queryBuf[MYSQLMAXLEN];
74     int pos;
75     queryBuf[0] = '\0';
76     va_start(arg_list, text);
77     pos = vsnprintf(queryBuf, MYSQLMAXLEN - 2, text, arg_list);
78     va_end(arg_list);
79     if (pos < 0 || pos > (MYSQLMAXLEN - 2)) pos = MYSQLMAXLEN - 2;
80     queryBuf[pos] = '\0';
81     printf("MySQL: %s\n", queryBuf);
82     if(mysql_query(mysql_conn, queryBuf)) {
83         show_mysql_error();
84     }
85 }
86
87 char* escape_string(const char *str) {
88     struct escaped_string *escapedstr = malloc(sizeof(*escapedstr));
89     if (!escapedstr) {
90         return NULL;
91     }
92     char escaped[strlen(str)*2+1];
93     mysql_real_escape_string(mysql_conn, escaped, str, strlen(str));
94     escapedstr->string = strdup(escaped);
95     escapedstr->next = escaped_strings;
96     escaped_strings = escapedstr;
97     return escapedstr->string;
98 }