-2

I'm trying to change the content of a string (from user's input), I'd like to remove any character that will let my query fail. For example, if I insert a second name with a " ' " in it, the query will fail.

Since I have to then output these rows from the DB, I'm wondering if there's any way to insert the string in the database while replacing the special character with its HTML value so that when I'm outputting it, the browser will do the rest.

I'm leaving you an example:

$string = $_POST['user_input']; // Let it be Lol'd
$sql = "INSERT INTO table(field) VALUES('$string')";

Now without anything done to the string I'd get the query as:

INSERT INTO table(field) VALUES('Lol'd')

What I'm looking for is something to turn the ' into ' so that in the DB it's saved Lol'd but when I echo it it'll just print Lol'd

Dankorw
  • 47
  • 10

2 Answers2

1

There are lot of solutions. You can use a function like htmlentities():

$string = htmlentities($_POST['user_input']); // Let it be Lol'd
$sql = "INSERT INTO table(field) VALUES('$string')";

To read the string from your MySQL table, use html_entity_decode()

-1

try this

$string = str_replace("'","\'",$_POST['user_input']); 
$sql = "INSERT INTO table(field) VALUES('$string')";
Ankur Bhadania
  • 4,123
  • 1
  • 23
  • 38
  • I used this in a previous work, but I was wondering if there was any function that will change ANY special character in HTML. I think that I may be leving a special character that the user might insert. – Dankorw Oct 31 '14 at 10:27
  • 1
    Maybe needless to say, but only filtering a `'` is not enough. Surely there are built-in function in PHP to sanitize input. – Jan Doggen Oct 31 '14 at 10:50