0

When I remove '$user' and by this works perfectly

$query = $db -> query("INSERT INTO posts (title, body, tags, published, date, by) VALUES       
('$title', '$body', '$tags', '$published', '$date', '$user')");

User is varchar(11)

when I print_r $user I get the value I want

I am not sure what is going on, by is at the end of the table.

Sorry if this question is stupid.

peace

billinkc
  • 59,250
  • 9
  • 102
  • 159

2 Answers2

7

Because BY is a Reserved keyword and happens to be the name of the column. In order to avoid syntax error, you need to escape it using backtick,

INSERT INTO posts (title, body, tags, published, date, `by`) VALUES (...)

I rather change the column name to avoid problem from getting back again :D


As a sidenote, the query is vulnerable with SQL Injection if the value(s) of the variables came from the outside. Please take a look at the article below to learn how to prevent from it. By using PreparedStatements you can get rid of using single quotes around values.

Community
  • 1
  • 1
John Woo
  • 258,903
  • 69
  • 498
  • 492
1

And addition, you can also put a backtick on the "date" column since it is also a reserved word..

INSERT INTO posts (title, body, tags, published, `date`, `by`) VALUES (...)

Well in my case I really don't prefer using backtick but it's really helpful in avoiding syntax errors..

catzilla
  • 1,901
  • 18
  • 31
  • you are right that `date` is a reserved keyword but it can be used even without wrapping it with backtick. – John Woo Apr 23 '13 at 03:15
  • 1
    yeah, you're also right! But well, in the case of formality and consistency, that can be applied.. well, it's true that it is not necessary though.. :) anyway, thanks for the reply and additional info.. – catzilla Apr 23 '13 at 03:36