I just started learning Lua/SQL a few days ago and pestered Megiddo with some questions, so I thought I'd give him a break and ask for help here.
I'm trying to set up a function that allows me to add new columns to an existing SQL table. Is this possible?
This is the non-functioning code I have thus far. It runs when a player joins the server, but I just realized it would probably be more efficient if it ran only once when the server booted up, so I'll have to modify it to do that.
sv_serverflags.lua
-- Create the SQL table if it doesn't exist
if not sql.TableExists( "server_flags" ) then
sql.Query( "CREATE TABLE IF NOT EXISTS server_flags ( id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, player INTEGER NOT NULL, initialflag INTEGER NOT NULL );" )
end
-- Set up the flags
local ServerFlags = {
"testflag1",
"testflag2",
"another_flag"
}
-- Add flags to the player if they don't already have them when they join the server
function FlagSetup( ply )
local uid = ply:UniqueID()
-- Make sure the player has a row in the table - blatantly plagiarized from UTime
local row = sql.QueryRow( "SELECT initialflag FROM server_flags WHERE player = " .. uid .. ";" )
if not row then
sql.Query( "INSERT into server_flags ( player, initialflag ) VALUES ( " .. uid .. ", " .. 1 .. " );" )
end
-- Cycle through the list of flags
for k,v in pairs(ServerFlags) do
local currentflag = sql.Query("SELECT " .. ServerFlags[k] .. " FROM server_flags WHERE player = " .. uid .. ";")
-- If the player doesn't have this flag in their row in the SQL db, add it
if not currentflag then
-- Add the column
sql.Query("ALTER TABLE server_flags ADD " .. Flags[k] .. " INTEGER NOT NULL WHERE player = " .. uid .. ";")
-- Make the flag value "0" (Hope this doesn't make everyone's Flag[k] value "0"...)
sql.Query("INSERT into server_flags (" .. Flags[k] .. ") VALUES (" .. 0 .. ");")
end
end
end
hook.Add( "PlayerInitialSpawn", "FlagSetup", FlagSetup)
I have pretty much no idea what I'm doing when it comes to SQL, so don't be afraid to treat me like a child in your explanation.
EDIT: Realized I forgot to assign "player" a value in the table, that would definitely be a problem. Added that fix.