local function close_db(db)
if not db then
return
end
db:close()
end
local mysql = require("resty.mysql")
local db, err = mysql:new()
if not db then
ngx.say("new mysql error : ", err)
return
end
db:set_timeout(1000)
local props = {
host = "127.0.0.1",
port = 3306,
database = "logs",
user = "root",
password = "root"
}
local res, err, errno, sqlstate = db:connect(props)
if not res then
ngx.say("connect to mysql error : ", err, " , errno : ", errno, " , sqlstate : ", sqlstate)
return close_db(db)
end
local table = os.date("log_%Y%m")
local create_table_sql = string.format("CREATE TABLE IF NOT EXISTS `%s` (`ip` CHAR(15) NULL DEFAULT NULL,`name` VARCHAR(256) NULL DEFAULT NULL,`status` TINYINT(1) NULL DEFAULT NULL,`msg` TEXT NULL DEFAULT NULL,`optime` DATETIME NULL DEFAULT CURRENT_TIMESTAMP)", table)
res, err, errno, sqlstate = db:query(create_table_sql)
if not res then
ngx.say("create table error : ", err, " , errno : ", errno, " , sqlstate : ", sqlstate)
return close_db(db)
end
local args = ngx.req.get_uri_args()
local args_ip = args["ip"] or 'null'
local args_name = args["name"] or 'null'
local args_status = args["status"] or 2
local args_msg = args["msg"] or 'null'
-- 防注入
local args_ip = ngx.quote_sql_str(args_ip)
local args_name = ngx.quote_sql_str(args_name)
-- 转换为int
local args_status_n = tonumber(args_status)
if args_status_n then
args_status = args_status_n
else
args_status = 3
end
local args_msg = ngx.quote_sql_str(args_msg)
local insert_sql = string.format("INSERT INTO `%s`(`ip`, `name`, `status`, `msg`) values (%s, %s, %d, %s)", table, args_ip, args_name, args_status, args_msg)
res, err, errno, sqlstate = db:query(insert_sql)
if res then
ngx.say('success')
else
ngx.say("insert error : ", err, " , errno : ", errno, " , sqlstate : ", sqlstate)
return close_db(db)
end
close_db(db)