In my opinion SQL injection is an major issue when it comes to web application development. Typically programmers deal with it by escaping strings, while this is probably the best way to get it handled i want to show you different yet effective approach to this problem – converting string to hex value.

Hex value consists of digits and letters from A to F, so this are “normal” chars which can be inserted safely into query, furthermore you can convert any string into hex value. It doesn’t matter what encoding you are going to use, or what kind of text you are converting (plain text, html, xml, etc).

Converting string to hex

Without any further ado here is a script for converting string into HEX. Actually i should credit someone for this code because i am not the one who wrote it in the first place but unfortunately i do not remember where i found it.

function strToHex($string)
{
    $hex='';
    for ($i=0; $i < strlen($string); $i++)
    {
        $hex .= dechex(ord($string[$i]));
    }
    return $hex;
}

Converting string to hex

Now converting backwards – hex to string.

function hexToStr($hex)
{
    $string='';
    for ($i=0; $i < strlen($hex)-1; $i+=2)
    {
        $string .= chr(hexdec($hex[$i].$hex[$i+1]));
    }
    return $string;
}

Well it all looks good and wonderful, but as always there are no roses without torns. First of all string converted to hex value is twice as long as original string. Second if you are going to use hex data in database then handling data may become a bit complicated.