PHP provides a function that we can use to escape value before submit query into database. See examples below.
// check whether the PHP support our code
if (function_exists('mysql_real_escape_string') AND is_resource($connection_id))
{
$str = mysql_real_escape_string($str, $connection_id);
}
elseif (function_exists('mysql_escape_string'))
{
$str = mysql_escape_string($str);
}
else
{
$str = addslashes($str);
}
$db_link = @mysql_connect('localhost', 'mysql_user', 'mysql_password');
if (!is_resource($db_link)) {
die('Connection error : ' . mysql_error());
}
From the example above, if $db_link is not a resource, it will return false, means the connection failed to establish.
Back to the Topic
mysql_real_escape_string is the best function to use if it is exist, but when the php version doesn't provide that function, we use mysql_escape_string, otherwise we can use addslashes to add back slashes ('\') to the value contains special characters like quotes.
When creating php based application, it is very recommended to use a framework like Code Igniter, Zend or Yii, etc. Because those frameworks can simplify our works, and provide more security to our system. But you must have a knowledge about using PHP as OOP, not only procedural. The first code above is based on the function called escape provided by Code Igniter.
0 comments:
Post a Comment