Why does this code produce an error
$sql = "INSERT INTO accountlist VALUES ("", "$user", "$pwd", "$mail", "$date")";
and this one doesn’t?
$sql = "INSERT INTO accountlist VALUES ('', '$user', '$pwd', '$mail', '$date')";
I know that double quotes process variables while single quotes doesn’t, so the first option should be the right one, but it is the opposite!
Advertisement
Answer
To answer your question instead of going on tangents about query parameters…
https://www.php.net/manual/en/language.types.string.php explains the mechanics of using quote characters inside quoted strings.
Basically, if your PHP string is delimited by "
, then the next "
character is the end of the string.
But you might want to use a literal double-quote character inside the string, but not to end the string. To do this, you can put a backslash in front of it like this:
$sql = "INSERT INTO accountlist VALUES ("", "$user", "$pwd", "$mail", "$date")";
Then the backslashed double-quote characters become part of the string content, not the delimiter for the end of the string.
But single-quote characters inside a double-quoted string won’t cause the same ambiguity, so they don’t need to be backslashed. Therefore the following works without error:
$sql = "INSERT INTO accountlist VALUES ('', '$user', '$pwd', '$mail', '$date')";
The parser can tell that single-quote is not the character it’s looking for to end the double-quoted string. So those single-quotes are parsed as literal characters.
This works the same way in many other programming languages, like Java, C, C++, Ruby, Python, Perl, and even in SQL itself.
This is why some people may sound impatient that you asked this question. It’s a very beginner-level question that indicates that you haven’t done enough reading of programming languages, and you’re expecting the community to give you personalized tutoring for concepts that you should get on your own.