Raised This Month: $ Target: $400
 0% 

[SNIPPET] Escape a char from a String (With SQL support)


Post New Thread Reply   
 
Thread Tools Display Modes
Author Message
dordnung
Veteran Member
Join Date: Apr 2010
Old 03-31-2013 , 08:07   [SNIPPET] Escape a char from a String (With SQL support)
Reply With Quote #1

Escape a char from a String (With SQL support)


Because the stock to escape a string is only possible with a database handle and also limited on the used SQL driver, i write an little snippet to escape a char from a string. Also i added two methods to escape a string for MySQL and SQLite.
This can be also useful if you want to convert the database from a driver to another.


PHP Code:
/**
 * Escapes a string from a char with a given escaper char
 *
 * @param input            The string to escape
 * @param escape        Char to escape
 * @param escaper        Char to escape with
 * @param output        Output string to store escaped string
 * @param maxlen        Size of the output string
 *
 * @return                 Number of escaped chars 
 */
stock EscapeString(String:input[], escapeescaperString:output[], maxlen)
{
    
// Number of chars we escaped
    
new escaped 0;

    
// Format output buffer to ""
    
Format(outputmaxlen"");


    
// For each char in the input string
    
for (new offset 0offset strlen(input); offset++)
    {
        
// Get char at the current position
        
new ch input[offset];

        
// Found the escape or escaper char
        
if (ch == escape || ch == escaper)
        {
            
// Escape the escape char with the escaper^^
            
Format(outputmaxlen"%s%c%c"outputescaperch);

            
// Increase numbers of chars we escaped
            
escaped++;
        }
        else
        {
            
// Add other char to output buffer
            
Format(outputmaxlen"%s%c"outputch);
        }
    }

    
// Return escaped chars
    
return escaped;
}

/**
 * Escapes string's ' or " chars with MySQL rules. Escape char is the \ char
 *
 * @param input            The string to escape
 * @param output        Output string to store escaped string
 * @param maxlen        Size of the output string
 * @param escape         True to escape ' char, false to escape " char
 *
 * @return                 Number of escaped chars 
 */
stock EscapeStringMySQL(String:input[], String:output[], maxlenbool:escape true)
{
    
// Number of chars we escaped
    
new escaped 0;


    
// Escape the ' char
    
if (escape)
    {
        
escaped EscapeString(input'\'''\\'outputmaxlen);
    }

    
// Escape the " char
    
else
    {
        
escaped EscapeString(input'"''\\'outputmaxlen);
    }


    
// Return escaped chars
    
return escaped;
}


/**
 * Escapes string's ' or " chars with SQLite rules. Escape char is the ' or " char
 *
 * @param input            The string to escape
 * @param output        Output string to store escaped string
 * @param maxlen        Size of the output string
 * @param escape         True to escape ' char, false to escape " char
 *
 * @return                 Number of escaped chars 
 */
stock EscapeStringSQLite(String:input[], String:output[], maxlenbool:escape true)
{
    
// Number of chars we escaped
    
new escaped 0;


    
// Escape the ' char
    
if (escape)
    {
        
escaped EscapeString(input'\'''\''outputmaxlen);
    }

    
// Escape the " char
    
else
    {
        
escaped EscapeString(input'"''"'outputmaxlen);
    }


    
// Return escaped chars
    
return escaped;


Here is a little test:


PHP Code:
#include <sourcemod>
#include <stringescape>


public OnPluginStart()
{
    
// Just some strings to escape
    
new String:firstString[] = "This is a normal string";
    new 
String:secondString[] = "Just use some ' chars, or more than one ' \'' '";
    new 
String:thirdString[] = "Just a \" \" escape it the \".. stupid \\\"\\\\\"";
    new 
String:fourthString[] = "We don't need the eeee, so escape them with a s";

    
// Just Escape
    
decl String:fourthOutput[sizeof(fourthString) * 2];

    
// Output buffers mysql, twice size should be enough
    
decl String:firstOutputMySQL[sizeof(firstString) * 2];
    
decl String:secondOutputMySQL[sizeof(secondString) * 2];
    
decl String:thirdOutputMySQL[sizeof(thirdString) * 2];

    
// Output buffers sqlite, twice size should be enough
    
decl String:firstOutputSQLite[sizeof(firstString) * 2];
    
decl String:secondOutputSQLite[sizeof(secondString) * 2];
    
decl String:thirdOutputSQLite[sizeof(thirdString) * 2];


    
// Just Escape
    
new escapedFourthChar EscapeString(fourthString'e''s'fourthOutputsizeof(fourthOutput));


    
// Now escape them :) First for mysql
    
new escapedFirstCharMySQL EscapeStringMySQL(firstStringfirstOutputMySQLsizeof(firstOutputMySQL));
    new 
escapedSecondCharMySQL EscapeStringMySQL(secondStringsecondOutputMySQLsizeof(secondOutputMySQL), true);
    new 
escapedThirdCharMySQL EscapeStringMySQL(thirdStringthirdOutputMySQLsizeof(thirdOutputMySQL), false);

    
// Now for sqlite
    
new escapedFirstCharSQLite EscapeStringSQLite(firstStringfirstOutputSQLitesizeof(firstOutputSQLite));
    new 
escapedSecondCharSQLite EscapeStringSQLite(secondStringsecondOutputSQLitesizeof(secondOutputSQLite), true);
    new 
escapedThirdCharSQLite EscapeStringSQLite(thirdStringthirdOutputSQLitesizeof(thirdOutputSQLite), false);

    
// Print result of first string
    
PrintToServer("The first string '%s' is escaped for MySQL = '%s' (%i chars escaped) and for SQLite = '%s' (%i chars escaped)"
            
firstStringfirstOutputMySQLescapedFirstCharMySQLfirstOutputSQLiteescapedFirstCharSQLite);


    
// Print result of second string
    
PrintToServer("The second string '%s' is escaped for MySQL = '%s' (%i chars escaped) and for SQLite = '%s' (%i chars escaped)"
            
secondStringsecondOutputMySQLescapedSecondCharMySQLsecondOutputSQLiteescapedSecondCharSQLite);


    
// Print result of third string
    
PrintToServer("The third string '%s' is escaped for MySQL = '%s' (%i chars escaped) and for SQLite = '%s' (%i chars escaped)"
            
thirdStringthirdOutputMySQLescapedThirdCharMySQLthirdOutputSQLiteescapedThirdCharSQLite);

    
// Print result of fourth string
    
PrintToServer("The fourth string '%s' is escaped with 's' = '%s' (%i chars escaped)"
            
fourthStringfourthOutputescapedFourthChar);

    
/*
    Output:
    
    The first string 'This is a normal string' is escaped 
        for MySQL = 'This is a normal string' (0 chars escaped) and for SQLite = 'This is a normal string' (0 chars escaped)
    
    The second string 'Just use some ' chars, or more than one ' '' '' is escaped 
        for MySQL = 'Just use some \' chars, or more than one \' \'\' \'' (5 chars escaped) and for SQLite = 'Just use some '' chars, or more than one '' '''' ''' (5 chars escaped)
    
    The third string 'Just a " " escape it the ".. stupid \"\\"' is escaped 
        for MySQL = 'Just a \" \" escape it the \".. stupid \\\"\\\\\"' (8 chars escaped) and for SQLite = 'Just a "" "" escape it the "".. stupid \""\\""' (5 chars escaped)
    
    The fourth string 'We don't need the eeee, so escape them with a s' is escaped 
        with 's' = 'Wse don't nsesed thse sesesese, sso sesscapse thsem with a ss' (14 chars escaped)

    */


I hope it's useful for you. Have fun

greetz Popoklopsi
Attached Files
File Type: inc stringescape.inc (2.6 KB, 713 views)
File Type: sp Get Plugin or Get Source (escape_test.sp - 438 views - 3.6 KB)
__________________

Last edited by dordnung; 04-04-2013 at 08:09.
dordnung is offline
ecca
Sexy Santa
Join Date: Jan 2011
Old 03-31-2013 , 10:41   Re: [SNIPPET] Escape a string for MySQL and SQLite
Reply With Quote #2

Could be in use if you don't have a connection setup as you mentioned ;) Good job.
__________________
ecca is offline
asherkin
SourceMod Developer
Join Date: Aug 2009
Location: OnGameFrame()
Old 03-31-2013 , 11:56   Re: [SNIPPET] Escape a string for MySQL and SQLite
Reply With Quote #3

It's idiotic to use this, if you need to insert text into a database, you're going to have a connection.
The driver-level functions are designed to escape exactly what's required.
__________________
asherkin is offline
dordnung
Veteran Member
Join Date: Apr 2010
Old 03-31-2013 , 11:58   Re: [SNIPPET] Escape a string for MySQL and SQLite
Reply With Quote #4

You don't always need escaped Strings for inserting. Maybe you just want to store a .sql file for importing (as i needed it, so i thought maybe someone else need it, too. Can't hurt...).
__________________

Last edited by dordnung; 03-31-2013 at 12:00.
dordnung is offline
alongub
Veteran Member
Join Date: Aug 2009
Location: Israel
Old 04-02-2013 , 00:18   Re: [SNIPPET] Escape a string for MySQL and SQLite
Reply With Quote #5

Quote:
Originally Posted by Popoklopsi View Post
You don't always need escaped Strings for inserting. Maybe you just want to store a .sql file for importing (as i needed it, so i thought maybe someone else need it, too. Can't hurt...).
If you're exporting a SQL file from a SM plugin, I strongly believe that you're doing something wrong.
__________________
alongub is offline
Powerlord
AlliedModders Donor
Join Date: Jun 2008
Location: Seduce Me!
Old 04-03-2013 , 20:03   Re: [SNIPPET] Escape a string for MySQL and SQLite
Reply With Quote #6

Quote:
Originally Posted by asherkin View Post
It's idiotic to use this, if you need to insert text into a database, you're going to have a connection.
The driver-level functions are designed to escape exactly what's required.
And just as importantly, since you didn't mention it: The standard SQL way of escaping is to replace ' with ''.

MySQL is more involved than that but it still supports using '' to escape '. I can't honestly say whether SQLite supports that.
__________________
Not currently working on SourceMod plugin development.

Last edited by Powerlord; 04-03-2013 at 20:05.
Powerlord is offline
dordnung
Veteran Member
Join Date: Apr 2010
Old 04-04-2013 , 08:08   Re: [SNIPPET] Escape a char from a String (With SQL support)
Reply With Quote #7

I updated the snippet, so you can generally escape a string from a char with a given escaper. And also the snippet is a lot of smaller.
__________________
dordnung is offline
rhelgeby
Veteran Member
Join Date: Oct 2008
Location: 0x4E6F72776179
Old 04-04-2013 , 13:27   Re: [SNIPPET] Escape a char from a String (With SQL support)
Reply With Quote #8

Code is clean and well formatted. However there are two improvements:
  • Move call to strlen() outside the loop to make the snippet as efficient as possible. Even calls to Format to concatenate strings are unnecessary if you work with strings as arrays. But that isn't a big deal.
  • When you call EscapeString multiple times in the SQL escaping functions, use the output from the last one as the input in the next one. Otherwise the last result will be overwritten.
__________________
Richard Helgeby

Zombie:Reloaded | PawnUnit | Object Library
(Please don't send private messages for support, they will be ignored. Use the forum.)

Last edited by rhelgeby; 04-04-2013 at 13:31.
rhelgeby is offline
Send a message via MSN to rhelgeby
ecca
Sexy Santa
Join Date: Jan 2011
Old 03-31-2013 , 12:14   Re: [SNIPPET] Escape a string for MySQL and SQLite
Reply With Quote #9

Asherkin, you maybe are inexperienced with php and still want to send information against a php code and then this will be functional.

Edit: You maybe not should be throwing you into deep water before you can swim.
__________________

Last edited by ecca; 03-31-2013 at 12:29.
ecca is offline
Zephyrus
Cool Pig B)
Join Date: Jun 2010
Location: Hungary
Old 03-31-2013 , 13:01   Re: [SNIPPET] Escape a string for MySQL and SQLite
Reply With Quote #10

Quote:
Originally Posted by ecca View Post
Asherkin, you maybe are inexperienced with php and still want to send information against a php code and then this will be functional.

Edit: You maybe not should be throwing you into deep water before you can swim.
using mysql_real_escape_string in PHP is easier than in sourcemod lol
__________________
Taking private C++/PHP/SourcePawn requests, PM me.
Zephyrus is offline
Reply



Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off

Forum Jump


All times are GMT -4. The time now is 18:38.


Powered by vBulletin®
Copyright ©2000 - 2024, vBulletin Solutions, Inc.
Theme made by Freecode