2

I am attempting to insert some user-inputted data into my MySQL table using the following command:

$sql = "INSERT INTO Queued ('$role') VALUES ('$sname')";

Interestingly enough, I get the following error:

Error: INSERT INTO Queued ('Tops') VALUES ('Summoner') You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near ''Tops') VALUES ('Summoner')' at line 1

To be honest, I am relatively new at using PHP as well as MySQL, but I can't seem to find the error in my syntax; the Queued table does exist, $role and $sname are both strings so I encased them in single quotes. I suspect this is a newbie mistake, could anyone point me in the right direction?

5
  • Use INSERT INTO Queued ($role), but better yet, use a prepared statement. Commented Jul 17, 2018 at 6:10
  • Ah, thanks that fixed the problem. Why do I need to exclude single quotes around $role but not $sname? Aren't they both interpreted as strings? Commented Jul 17, 2018 at 6:12
  • Yes, they are both interpreted as strings, but that happens with or without single quotes. Column names don't take single quotes in MySQL (or really in any other database). Commented Jul 17, 2018 at 6:12
  • Ah gotcha, thanks for the explanation! Commented Jul 17, 2018 at 6:14
  • Possible duplicate of When to use single quotes, double quotes, and back ticks in MySQL Commented Jul 17, 2018 at 6:28

3 Answers 3

2

This is due to use of single quotes ' around the column name. The query should be like:

$sql = "INSERT INTO Queued ($role) VALUES ('$sname')";

OR

$sql = "INSERT INTO Queued (`$role`) VALUES ('$sname')";
Sign up to request clarification or add additional context in comments.

3 Comments

What is the role of the `s around $role? Interpret this as non-SQL?
The OP should be using a statement, and this isn't the best answer which can be given. Also, backticks around $role aren't needed.
` are usually used around column names in mysql query.
0

Try this format

$sql = "INSERT INTO Queued ('".$role."') VALUES ('".$sname."')";

Comments

0

`s role is to differentiate between built in SQL words and the column names, so if a word is used for name of a column that might be also a built in sql expression then `` are needed around it

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.