Small LuaSQL tutorial made by Jonern.
This is just a little example of how to use LuaSQL in The Forgotten Server (0.2.5 and up)
First, you need to create an environment object. This is done like this:
Now you need to connect to the database. This is done like this:
Now that the connection is done, you can start doing queries.
Lets say we want to show in a window wich players that is over level 100 (to make it simple).
Then we need to do a query to the database. And we need to put the data together a way we can use it.
So let's put it all together, but first, we would like to get the database name, user, pw and so on from config.lua. This is quite easily done, just add in the beginning of the script:
Lets put it all together:
This script is tested, and works, but is just a simple example.
There are also other functions to use in LuaSQL such as cur:numrows(). Look here for more functions and information.
Don't forget to give REP! (My first tutorial ^_^)
This is just a little example of how to use LuaSQL in The Forgotten Server (0.2.5 and up)
First, you need to create an environment object. This is done like this:
Code:
env = assert(luasql.mysql()) -- change mysql to sqlite3 if you use SQLite
Code:
con = assert(env:connect("databaseName", "user", "password", "host OR ip", "port")) -- if port is 3306, you dont need that part.
Lets say we want to show in a window wich players that is over level 100 (to make it simple).
Then we need to do a query to the database. And we need to put the data together a way we can use it.
Code:
cur = assert(con:execute("SELECT `name`, `level` FROM `players` WHERE `level` >= 100;")) -- This is how you execute queries. You should give them the variable name "cur" as in "current".
row = cur:fetch({}, "a") -- {} is where to store the result, in this case it's making a table of the variable 'row'. "a" means that the rows will be indexed by field names.
while row do
str = str .. "\n" .. row.name .. " [" .. row.level .. "]" -- this is to put the lines together into one string.
-- reusing the table of results
row = cur:fetch (row, "a")
end
doPlayerPopupFYI(cid, "List of players level 100 or higher:\n\n" .. str)
Code:
dofile("./config.lua")
Code:
function onSay(cid, words, param)
dofile("./config.lua")
env = assert(luasql.mysql())
con = assert(env:connect(mysqlDatabase, mysqlUser, mysqlPass, mysqlHost, mysqlPort))
cur = assert(con:execute("SELECT `name`, `level` FROM `players` WHERE `level` >= 100;"))
row = cur:fetch({}, "a")
local str = ""
while row do -- a loop to go trough all rows.
str = str .. "\n" .. row.name .. " [" .. row.level .. "]"
-- reusing the table of results
row = cur:fetch (row, "a")
end
doPlayerPopupFYI(cid, "List of players level 100 or higher:\n\n" .. str) -- Opens a window and lists the players
end
There are also other functions to use in LuaSQL such as cur:numrows(). Look here for more functions and information.
Don't forget to give REP! (My first tutorial ^_^)
Last edited: