Why it is recommended to put single or double quotes around HTML attribute values? It is recommended to prevent XSS, but why?

Same goes for SQL injection: It is recommended to use single or double quotes while declaring input values in a query?

What risks are associated with declaring unquoted input values in a SQL query or HTML attribute?

2 Answers 2


Without quotes, the payload would escape the actual attribute's value and will start a new attribute with its own payload:

<div class=fist onclick=console.log(document.cookie)>

Whereas with quotes it will remain a harmless single attribute value:

<div class="fist onclick=console.log(document.cookie)">

Note that to prevent XSS you must encode the special characters inside the value as well.

For the SQL injection the situation is different. It is strictly not recommended to declare input values in the query in the first place.

To prevent an SQL injection, a parameter must be defined in the query in place of the actual value, which must be sent to the query execution separately:

$stmt->prepare("SELECT * FROM t WHERE id=?");

Therefore, there must be not a single quote in the query related to the dynamically added value, which makes the question on quotes just irrelevant.

  • Unless the payload is fist " onclick="console.log(document.cookie). "must encode the special characters " is key here.
    – Ajedi32
    Nov 6, 2018 at 17:07
  • Both actions are "the key". Both useless without each other. You must both quote and escape. So your idea to emphasize only one is wrong. Nov 7, 2018 at 6:48
  • Actually, no. If you properly escape whitespace characters, quotes are technically not necessary (though I would still recommend them for readability). See: html.spec.whatwg.org/multipage/syntax.html#attributes-2. Your answer is still correct; I just wanted to emphasize that the OP's assumption that "quotes prevent XSS" is flawed so that future readers (who might not be reading very carefully) don't get the idea that everything's fine as long as you properly quote your attributes.
    – Ajedi32
    Nov 7, 2018 at 14:43

Never rely on quotes to protect you against code injection. Not in HTML, and certainly not in SQL.

An attacker who has the ability to inject arbitrary, unescaped strings into your source code has already won, regardless of what characters you use to wrap that unfiltered text.

Instead, use whatever system the language or framework you're using has built to handle user input. In pure SQL, that's probably parameterized queries. In HTML rendered by PHP, htmlspecialchars. In client-side JavaScript, Element.setAttribute. Find out what system your language/framework provides and use it. Don't just surround arbitrary text in quotes (single or double) and assume that will work; it probably won't.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .