Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to insert a string that contains quote marks into a database?

Tags:

php

mysql

When I try to instert a string that contains a quote mark, the INSERT query fails. How can I insert strings with single or double quotes?

for example:

$message = "Bob said 'don't forget to call me'";

mysql_query("INSERT INTO someTable (messages) VALUES ('$message')");

I figure the input needs to be filtered but which function should I use for that?

like image 896
Sam Avatar asked Jun 26 '10 02:06

Sam


2 Answers

See: mysql_real_escape_string

You should ALWAYS be escaping things anything provided by the user before they go it goes into the database to prevent SQL injection in any case.

like image 154
Billy ONeal Avatar answered Sep 25 '22 10:09

Billy ONeal


$message = mysql_real_escape_string($message);

this function should be applied to every variable you are going to insert into query in quote marks. No exceptions.
It is not really protection from sсaring injection but just a syntax rule.

Though you will need a real protection too. I've explained that in detail in recent answer: In PHP when submitting strings to the database should I take care of illegal characters using htmlspecialchars() or use a regular expression?

like image 42
Your Common Sense Avatar answered Sep 26 '22 10:09

Your Common Sense