0

when I try to remove special characters in a variable using the addcslashes eg addcslashes($this->description), "description" save the record in database but empty. If I remove addcslashes and just use $this->description saves normally.

Anderson Nunes
  • 201
  • 3
  • 18
  • for what do you need it then? – Rufinus Sep 24 '14 at 22:22
  • Did you read the [documentation for `addcslashes`](http://www.php.net)? I'd guess not since it specifies **2** arguments, but you've only used one. Are you thinking of [`addslashes`](http://www.php.net/addslashes)? – h2ooooooo Sep 24 '14 at 22:26
  • please don't use addslashes to sanitise input into the db –  Sep 24 '14 at 22:27
  • @h2ooooooo I think he tried, but closed the parenthesis too early – andrew Sep 24 '14 at 22:29
  • **Warning:** *Do not use addslashes to "santize" data* - addslashes should almost *never* be used, and *never* as an attempt to prevent SQL Injection. [Use placeholders with SQL](http://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php?rq=1) and use htmlentities for emitting data to HTML. – user2864740 Sep 24 '14 at 22:30

1 Answers1

0

Maybe, you can use this function:

function clean($string) {
   $string = str_replace(' ', '-', $string); // Replaces all spaces with hyphens.
   $string = preg_replace('/[^A-Za-z0-9\-]/', '', $string); // Removes special chars.

   return preg_replace('/-+/', '-', $string); // Replaces multiple hyphens with single one.
}

First sanitise the string before you send to save in DB.

  • 1
    This is a terrible function to use to "sanitize" data - first off, it loses most of the actual information that might be found in a description and is most likely incorrect for the use-case provided. And then it misses the real solutions: [use placeholders (correct approach)](http://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php?rq=1) or use mysql_real_escape_string (old but "it works" approach) for inserting data. – user2864740 Sep 24 '14 at 22:33