-4

i have a simple php INSERT INTO SQL statement that simply refuses to update several columns at once. i have no idea why but the following statement is acceptabel;

$sql = "INSERT INTO niceTable (first) VALUES ('Hello')";

however if i try to following

$sql = "INSERT INTO niceTable (first, last) VALUES ('Hello', 'You')";

it breaks down and throws the following error:

"Error updating record: 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 'desc) VALUES ('Hello', 'update')' at line 1"

I have checked the syntax, but it seems ok. I am using a one.com server. Anyone got any tips?

Sean Lange
  • 33,028
  • 3
  • 25
  • 40
Saucepan
  • 298
  • 1
  • 6
  • 19

3 Answers3

2

As per your "posted code":

The reason being that first and last are MySQL reserved words

and require special attention.

Either wrap them in ticks or rename them to something other than reserved keywords.

INSERT INTO niceTable (`first`, `last`)

Edit: However, your error doesn't support the issue here, nor the column name(s):

for the right syntax to use near 'desc)

this tells me you are using desc which is also another MySQL reserved word.

You should also use prepared statements

Plus, should your inputs contain characters that MySQL may complain about such as apostrophes John O'Neil then you will need to escape those values.

MySQL will interpret that as ('Hello', 'John O'Neil') in turn causing another syntax error.

Escaping it, would interpret it as ('Hello', 'John O\'Neil') making it valid.

  • I'm thinking ahead here.
Funk Forty Niner
  • 74,450
  • 15
  • 68
  • 141
2

Your actual query (not the one in your question) seems different. The error message seems to have desc somewhere, which is a reserved word. If you use reserve words as column names (don't), you should enclose them in backticks:

INSERT INTO tbl (`order`, `desc`) VALUES ('foo', 'bar');
Bart Friederichs
  • 33,050
  • 15
  • 95
  • 195
1

Enclose your column names in backticks

Last is a function in MySQL

$sql = "INSERT INTO niceTable (`first`, `last`) VALUES ('Hello', 'You')";
Funk Forty Niner
  • 74,450
  • 15
  • 68
  • 141
Geoff Atkins
  • 1,693
  • 1
  • 17
  • 23