You can use htmlentities()
to convert html elements into html entities and this function accepts a third argument which is for escaping single and double quotes.
Here is the signature of the function:
string htmlentities ( string $string [, int $flags = ENT_COMPAT [, string $charset [, bool $double_encode = true ]]] )
and the arguments that second parameters may take:
ENT_COMPAT Will convert double-quotes and leave single-quotes alone.
ENT_QUOTES Will convert both double and single quotes.
ENT_NOQUOTES Will leave both double and single quotes unconverted.
ENT_IGNORE Silently discard invalid code unit sequences instead of returning an empty string. Added in PHP 5.3.0. This is provided for backwards compatibility; avoid using it as it may have security implications.
And
You can simply use addslashes()
with htmlentities()
and also there is another function with cleans html tags out from the fields which is filter_var ()
and such example look would be:
$return_value = filter_var($data_to_be_filtered,FILTER_SANITIZE_STRING);
Important
Don't forget to check whether magic_quotes are enabled or not. You can do that by writing :
if(get_magic_quotes_gpc())
//do something
More about magic_quotes: http://www.php.net/manual/en/info.configuration.php#ini.magic-quotes-gpc
Edit:
You can do more secure transaction by using prepared-statements. They prevent SQL-Injection.
Sample code:
$db = new mysqli();
$db->real_connect($host,$username,$password,$db) or die("Cannot connect");
$query = "select name from users where id = ?";
$st = $db->prepare($query); //faster than normal query run
$st->bind_param("d",$id);
$st->execute();
$st->bind_result($name);
$st->fetch();
echo $name;