note 47881 added to function.mysql-real-escape-string
| From: | r dot haeder at will-hier-weg dot de | Date: | Fri, 03 Dec 2004 17:39:07 +0000 |
| Subject: | note 47881 added to function.mysql-real-escape-string | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-81332@lists.php.net to get a copy of this message | ||
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());
}
?>
----
Manual Page -- http://www.php.net/manual/en/function.mysql-real-escape-string.php
Edit -- http://master.php.net/manage/user-notes.php?action=edit+47881
Delete -- http://master.php.net/manage/user-notes.php?action=delete+47881&report=yes
Reason: bad code -- http://master.php.net/manage/user-notes.php?action=delete+47881&report=yes&reason=bad+code
Reason: spam -- http://master.php.net/manage/user-notes.php?action=delete+47881&report=yes&reason=spam
Reason: useless example -- http://master.php.net/manage/user-notes.php?action=delete+47881&report=yes&reason=useless+example
Reason: contains commercial links -- http://master.php.net/manage/user-notes.php?action=delete+47881&report=yes&reason=contains+commercial+links
Reason: useless note -- http://master.php.net/manage/user-notes.php?action=delete+47881&report=yes&reason=useless+note
Reject -- http://master.php.net/manage/user-notes.php?action=reject+47881&report=yes
Search -- http://master.php.net/manage/user-notes.php