I’m getting the following error whenever I try to post something with an apostrophe in it:
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near...
For example when I’m trying to post/using INSERT something like “I’m working hard”.It’s getting me an error. If I write “I am working hard” everything is fiine.
The code is:
$sql="INSERT INTO tb_table (`postcontent`, `userid`, `posttime`) VALUES ('".$_POST[content]."', '".$user_id."', '".time()."')";
Any ideas how to fix it?
That’s because you are using apostrophes to show MySQL where each value for the field starts and ends. If you put an apostrophe in the middle of the string, suddenly the database thinks that you’re trying to put in four values in three table fields, or some such thing.
It looks like you’re using PHP to insert data in the database so I’ll give you a couple of examples of dealing with this with the means that PHP provides.
A quick way to fix it to use mysql_real_escape_string():
A better approach would be to use prepared statements:
P.S. You don’t need single quotes around time() – this is a number, it’s safe to insert as is.