note 47881 deleted from function.mysql-real-escape-string by aidan
| From: | aidan@php.net | Date: | Sun, 26 Dec 2004 12:37:59 +0000 |
| Subject: | note 47881 deleted from function.mysql-real-escape-string by aidan | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-82311@lists.php.net to get a copy of this message | ||
Note Submitter: r dot haeder at will-hier-weg dot de
----
There is also a good way to secure your script against SQL injections. I found this one in the
"Linux-Magazin" which is a well-known magazine for european penguins.
<?php
//
// SQL string escaping function
//
// $qstring - The final SQL query string which is ready-to-go for the
// sprintf command
// $data_array - Simple indexed array which contains the data we
// want to insert into the SQL string
//
// Returns: Result of mysql_query() command
//
function SQL_QUERY_ESC($qstring, $data_array)
{
// $link shall be a valid link resource like you can get by:
// $link = @mysql_connect($host, $user, $password);
global $link;
$eval = "\$query = sprintf(\"".$qstring."\"";
$func = "mysql_real_escape_string"; $ADD = ", \$link";
if (!function_exists(mysql_real_escape_string))
{
// Older versions of PHP4 doesn't have this function???
$func = ""; $ADD = ""; // Quick'n'dirty fix!
}
// Add every array element "in a row" to the eval-string
foreach ($data_array as $var)
{
if ($var != "")
{
// Strip-out tags and add slashes
$eval .= ",
".$func."(\"".addslashes(strip_tags($var))."\"".$ADD.")";
}
else
{
// Add "nothing" but which has to be done
$eval .= ", ''";
}
}
// Close the sprintf() command...
$eval .= ");";
// Finally "eval" the constructed PHP4 code...
eval($eval);
// ... for quering it to the MySQL server:
return @mysql_query($query) or die(mysql_error());
}
?>