Skip to main content
Inspiring
July 2, 2018
Answered

PHP and special characters

  • July 2, 2018
  • 1 reply
  • 1746 views

Hi,

I am having trouble with an HTML simple text input form that where the  user may enter special characters such as single quote or double quote etc.

form text example: I'm Feeling good.

When processing the form - php - post to mysql DB shows the error :

Syntax error or access violation: 1064 You have an error in your SQL syntax...

the value it got was like:

'I'm Feeling good',

- which has 3 single quotes - causing the error...

Q: Is there a way to properly escape whatever the special characters are that might be type to fix this issue for php?

Thanks

Dave

This topic has been closed for replies.
Correct answer David_Powers

The best way to handle this would be to use a prepared statement. Prepared statements are supported by MySQLi and PDO.

An alternative approach (not as good) would be to pass the text input to htmlentities() before adding it to the SQL. To convert both single and double quotes, you need to use ENT_QUOTES as the second argument:

$text = htmlentities($text, ENT_QUOTES);

1 reply

David_Powers
David_PowersCorrect answer
Inspiring
July 2, 2018

The best way to handle this would be to use a prepared statement. Prepared statements are supported by MySQLi and PDO.

An alternative approach (not as good) would be to pass the text input to htmlentities() before adding it to the SQL. To convert both single and double quotes, you need to use ENT_QUOTES as the second argument:

$text = htmlentities($text, ENT_QUOTES);

revdaveAuthor
Inspiring
July 3, 2018

Thank you so much David! I had forgotten about  Prepared statements. I already was using PDO and now that I added Prepared statements along with $stmt->bindParam( .... now all is working well.

THANKS AGAIN,

Dave