Pergunta

I have looked at a bunch of different sites and I really don't want to spam y'all. But I'm really desperate and have nowhere else to turn. So here goes...

I am trying to let people post things on my website. And the tutorial I watched told me to use htmlspecialchars() so that people can post things such as greater/less than signs and special symbols and such without breaking anything. But whenever my mysql_query() encounters a single or double quote it throws this error:

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 't do this. I won' at line 1

Here is my corresponding code:

$sql = mysql_query("INSERT INTO stories (title, content, username, date_posted) VALUES ('$title', '$content', '$un', now())") or die(mysql_error());

And here's where I used the htmlspecialchars():

$content = $_POST['content'];
$content = nl2br(htmlspecialchars($content));

What am I supposed to do to fix this? Please help me.

-Sam

Foi útil?

Solução

htmlspecialchars() encodes HTML entities in strings like:

  • '&' (ampersand) becomes & (taken from PHP wiki)

However, SQL may not like some of the characters that are encoded, therefore you must mysql_real_escape_string() the $content as well.

Keep in mind however that MySQL is deprecated as of PHP 5.5.0, thus I suggest you to use MySQLi or PDO.

For more information: http://php.net/mysql_real_escape_string

In order to have you stuff again written in proper HTML once you load it, you must use htmlspecialchars_decode().

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top