Thread: [Solved] Sql Query Insert Problem
View Single Post
asherkin
SourceMod Developer
Join Date: Aug 2009
Location: OnGameFrame()
Old 01-12-2019 , 06:55   Re: Sql Query Insert Problem
Reply With Quote #8

Quote:
Originally Posted by ThatKidWhoGames View Post
Database.Format automatically escapes any strings that you want to format into a query. If you want to use the standard Format function for formatting an SQL query, you would have to escape the string first and then format the query. Someone can probably explain this better than I can.
Basically, it is really hard to do per-variable escaping correctly.

Taking the simple example of updating a players name stored in a database against a SteamID:

Using Database.Escape correctly looks like this:
PHP Code:
char name[MAX_NAME_LENGTH];
if (!
GetClientName(clientnamesizeof(name))) {
  return 
false;
}

int safeNameLen = (strlen(name) * 2) + 1;
char[] safeName = new char[safeNameLen];
db.Escape(namesafeNamesafeNameLen);

char steamId[32];
if (!
GetClientAuthId(clientAuthId_Steam2steamIdsizeof(steamId))) {
  return 
false;
}

int safeSteamIdLen = (strlen(steamId) * 2) + 1;
char[] safeSteamId = new char[safeSteamIdLen];
db.Escape(steamIdsafeSteamIdsafeSteamIdLen);

char buffer[512];
Format(buffersizeof(buffer), "UPDATE players SET name = '%s' WHERE steamid = '%s'"safeNamesafeSteamId);
db.Query(OnQueryCompletebuffer); 
Whereas using Database.Format looks like this:
PHP Code:
char steamId[32];
if (!
GetClientAuthId(clientAuthId_Steam2steamidsizeof(steamid))) {
  return 
false;
}

char buffer[512];
db.Format(buffersizeof(buffer), "UPDATE players SET name = '%N' WHERE steamid = '%s'"clientsteamId);
db.Query(OnQueryCompletebuffer); 
It is a lot shorter and harder to get wrong.
__________________
asherkin is offline