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?

Webdesky
  • 23
  • 2
  • Use `INSERT INTO Queued ($role)`, but better yet, use a prepared statement. – Tim Biegeleisen Jul 17 '18 at 06: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? – Tristan Melton Jul 17 '18 at 06: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). – Tim Biegeleisen Jul 17 '18 at 06:12
  • Ah gotcha, thanks for the explanation! – Tristan Melton Jul 17 '18 at 06:14
  • Possible duplicate of [When to use single quotes, double quotes, and back ticks in MySQL](https://stackoverflow.com/questions/11321491/when-to-use-single-quotes-double-quotes-and-back-ticks-in-mysql) – Nigel Ren Jul 17 '18 at 06:28

3 Answers3

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')";
Lovepreet Singh
  • 4,792
  • 1
  • 18
  • 36
0

Try this format

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

Hussain
  • 91
  • 9
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

firashelou
  • 131
  • 9