ServersYour serverFor creatorsForumFAQDocumentationSecurity
Download the launcher
  1. Documentation
  2. Server functions
  3. dbFetch

Function

dbFetch

ServerDatabaseTrilogy Hub only

Runs a query and returns its result right away. One call instead of dbQuery, dbPoll and dbFree. Works with SELECT, INSERT, UPDATE and DELETE.

Syntax

table dbFetch(element connection, string query, mixed ...)

Arguments

connectionelement
A handle from dbConnect.
querystring
SQL query with ? in place of values.
...mixed
Values for the ? placeholders, safely quoted.

Returns

A table of rows (each row is column = value). It also has rows.insertId (the inserted row's ID), rows.affectedRows (the number of changed rows) and rows.columns (the column names in order). On error false and the error message.

Example

local db = dbConnect("mysql", "glowna")

addCommandHandler("top", function(player)
    async(function()
        local rows, err = dbFetch(db, "SELECT nick, kasa FROM gracze ORDER BY kasa DESC LIMIT 5")
        if not rows then
            outputChatBox("Błąd bazy: " .. err, player)
            return
        end
        for i, row in ipairs(rows) do
            outputChatBox(i .. ". " .. row.nick .. " - $" .. row.kasa, player)
        end
    end)
end)

addCommandHandler("rejestracja", function(player)
    async(function()
        local result = dbFetch(db, "INSERT INTO gracze (nick, kasa) VALUES (?, ?)", getPlayerName(player), 500)
        if result then
            outputChatBox("Twoje konto ma numer " .. result.insertId, player)
        end
    end)
end)

Notes

Easiest inside async. In an async(function() ... end) task the server does not wait for the database: only that task is paused while the game and other scripts keep running. Outside a task dbFetch works too, but the server stands still until the database answers. With fast SQLite that does not matter, with MySQL use async.

The insertId and affectedRows fields stay out of the way. ipairs, pairs and #rows see only the rows. A NULL value from the database arrives as false.

See also