Alright, this is my first attempt at making a plugin that involves MySQL. Is everything here correct? It's not storing anything into the database.
Code:
#include <amxmodx>
#include <amxmisc>
#include <dbi>
public plugin_init() {
register_plugin("Store user info","0.1","v3x")
register_clcmd("storeinfo","doInsert")
set_task(0.1,"sql_init")
}
new Sql:dbc
new Result:result
new Result:userexists
public sql_init() {
new host[64], username[32], password[32], dbname[32], error[32]
get_cvar_string("amx_sql_host",host,63)
get_cvar_string("amx_sql_user",username,31)
get_cvar_string("amx_sql_pass",password,31)
get_cvar_string("amx_sql_db",dbname,31)
dbc = dbi_connect(host,username,password,dbname,error,31)
if(dbc == SQL_FAILED) {
log_amx("[AMXX] Failed to connect to DB")
} else {
dbi_query(dbc,"CREATE TABLE IF NOT EXISTS `userinfo` (`name` VARCHAR(32) NOT NULL,`steamid` VARCHAR(32) NOT NULL,`ip` VARCHAR(63) NOT NULL,`num` INT NOT NULL, PRIMARY KEY(`steamid`))")
}
}
public client_connect(id) {
new steamid[32]
get_user_authid(id,steamid,31)
new name[32]
get_user_name(id,name,31)
new ip[64]
get_user_ip(id,ip,63,1)
new num[32]
userexists = dbi_query(dbc,"SELECT steamid FROM userinfo WHERE steamid = '%s'",steamid)
if(userexists) {
result = dbi_query(dbc,"UPDATE connects SET num=num+1 WHERE steamid = '%s'",steamid)
dbi_free_result(result)
}
else if(!userexists) {
num[31] = 1
result = dbi_query(dbc,"INSERT INTO userinfo (name,steamid,ip,num) values ('%s','%s','%d','%d')",name,steamid,ip,num)
dbi_free_result(result)
}
dbi_free_result(userexists)
return PLUGIN_HANDLED
}
public doInsert(id) { // Used for testing!
new steamid[32]
get_user_authid(id,steamid,31)
new name[32]
get_user_name(id,name,31)
new ip[64]
get_user_ip(id,ip,63,1)
new num[32]
userexists = dbi_query(dbc,"SELECT * FROM userinfo WHERE steamid = '%s'",steamid)
if(dbc == SQL_FAILED) {
console_print(id,"[AMXX] Couldn't connect to MySQL server!")
}
if(dbc == SQL_OK) {
console_print(id,"[AMXX] Connected to the MySQL server")
}
if(dbi_num_rows(userexists) < 1) {
num[31] = 1
result = dbi_query(dbc,"INSERT INTO userinfo (name,steamid,ip,num) values ('%s','%s','%s','1')",name,steamid,ip)
if(result == RESULT_OK)
console_print(id,"[AMXX] Success!")
else if(result == RESULT_FAILED)
console_print(id,"[AMXX] Success!")
dbi_free_result(result)
}
else {
result = dbi_query(dbc,"UPDATE connects SET num=num+1 WHERE steamid = '%s'",steamid)
switch(result) {
case RESULT_OK: console_print(id,"[AMXX] Success (updated)!")
case RESULT_FAILED: console_print(id,"[AMXX] Failed to update")
}
dbi_free_result(result)
}
dbi_free_result(userexists)
return PLUGIN_HANDLED
}