[Tutorial] Handling utf8 data from database
#1

I found answer to my problem in an archive of russian section, so I guess I should share about it. Let's say you have database encoded in utf8_unicode_ci. Now, how to retrieve this data and show it properly in dialog? We'll use blueg mysql plugin.

1. Fetch and install utf8 plugin by Ryder - https://sampforum.blast.hk/showthread.php?tid=223944
pawn Code:
static dbhandle;
public OnGameModeInit() {
    dbhandle = mysql_connect(DB_HOST, DB_USER, DB_NAME, DB_PASS);
    if(mysql_ping()) {
        printf("Mysql connection succeeded");
        mysql_set_charset("utf8_unicode_ci", dbhandle);
        mysql_function_query(dbhandle, "SET NAMES 'utf8'", false, "", "");
    }
    return 1;
}
When your gamemode connects to database, we have to tell it that we're going to use utf8 encoding. Let's say that we have greeting for each user.

pawn Code:
public OnPlayerConnect(playerid) {
    new name[MAX_PLAYER_NAME+1], tmp[57 + MAX_PLAYER_NAME];
    GetPlayerName(playerid, name, sizeof name);
    mysql_format(dbhandle, tmp, "SELECT greeting FROM `users` WHERE uname = '%s' LIMIT 0,1", name);
    mysql_function_query(dbhandle, tmp, true, "GreetPlayer", "i", playerid);
    return 1;
}
forward GreetPlayer(pid);
public GreetPlayer(pid) {
    new rows, fields, tmp[32], msg[128];
    cache_get_data(rows, fields, dbhandle);
    if(rows) {
        cache_get_row(0, 0, tmp, dbhandle);
        UTF8_Decode(tmp, tmp, sizeof tmp);
        format(msg, sizeof msg, "%s!", tmp);
        ShowPlayerDialog(pid, 1231, DIALOG_STYLE_MSGBOX, "Hell yeah", msg, "k", "");
    }
    return 1;
}
As you can see we need to decode message retrieved from database, otherwise you'll gibberish
Reply


Forum Jump:


Users browsing this thread: 1 Guest(s)