Skip to content

Prepared Statements

imshooter edited this page Nov 29, 2026 · 1 revision

A prepared statement is sent to the server once and then run with values that are never escaped or parsed again. Its text takes the specifiers of queries, each one a value.

new
    MySQL:gDatabase,
    Statement:gSaveScore,
    gPlayerId[MAX_PLAYERS]
;

stock PrepareStatements() {
    gSaveScore = mysql_stmt_prepare(gDatabase, "UPDATE players SET score = %i WHERE id = %i");
}

stock SaveScore(playerid) {
    mysql_stmt_execute(gSaveScore, "", "", GetPlayerScore(playerid), gPlayerId[playerid]);
}

stock SaveScores() {
    new const
        Batch:batch = mysql_batch_create(gSaveScore)
    ;

    for (new i; i != MAX_PLAYERS; ++i) {
        if (IsPlayerConnected(i)) {
            mysql_batch_add_row(batch, GetPlayerScore(i), gPlayerId[i]);
        }
    }

    mysql_batch_execute(batch);
}

mysql_stmt_execute runs it once, the values of the public first and those of the statement after, and mysql_stmt_query waits for it. A statement runs on the connection of its handle that runs ordered queries, and is prepared again when the connection is lost or the tables change.

Batches

mysql_batch_create starts a batch, mysql_batch_add_row copies a row of values into it, and mysql_batch_execute sends them. On MariaDB 10.2 or later the rows go to the server as arrays in one command, split to fit max_allowed_packet, and on other servers they run one by one. A batch sent in more than one command runs in a transaction of its own, unless one is open already.

Home

Guides

Reference

Functions

Connections
Queries
Cache
JSON cells
ORM
Queries built in pieces
Prepared statements
Batches
Transactions
Passwords
Callbacks

Clone this wiki locally