[thelist] Re: Avoiding SQL Injection

Phil Turmel philip at turmel.org
Mon Mar 21 23:53:35 CST 2005


Brooking, John wrote:
[snip]
>    $sqlText = "INSERT INTO comments ( comment ) VALUES ( '" 
>             . $_POST["comment"] . "' )";
>             
[/snip]

If parameter objects in MS ADO or MySQLi are not an option, try PHP's 
other canned solutions for this (PHP 4.0.3 and up):

$sqlText = "INSERT INTO comments ( comment ) VALUES ( '" . 
mysql_escape_string( $_POST["comment"] ) . "' )";

which converts anything in the string to the appropriate escape 
sequences, presuming binary or pure ASCII data.  Or better yet:

$sqlText = "INSERT INTO comments ( comment ) VALUES ( '" . 
mysql_real_escape_string( $_POST["comment"], $link_id ) . "' )";

which does the same, but takes into account the current character set 
for the $link_id specified.

Details here:

http://us2.php.net/manual/en/function.mysql-real-escape-string.php

The PostgreSQL module has similar functions:

http://us2.php.net/manual/en/function.pg-escape-string.php

For other databases, use the generic addslashes:

http://us2.php.net/manual/en/function.addslashes.php

HTH,

Phil


More information about the thelist mailing list