hiiii friends,

i have a table messages whose columns are

id(primary key,auto increment) from to sub body

now when i am trying to insert in the table with the following syntax

insert into messages values(2,'$from','$to','$sub','$body')
it is working fine.

but since the id is in auto increment mode i am using the following syntax

insert into messages(from,to,subject,body) values('$from','$to','$sub','$body')

i am getting an error that there is a sql syntax error plz chek the manual for correct syntax.


can u help me in solving this

Dani AI

Generated

A short, practical summary and fixes for 's error.

Using SQL keywords as column names (for example the words you used for sender/recipient) is what triggered the syntax error. pointed to identifier quoting as a fix and noted the creation issue. Two safe approaches: rename the columns to non-reserved names, or quote identifiers whenever you use them. Renaming is the cleaner long-term solution.

Example of renaming columns (runs once, adjust types/lengths as needed):

ALTER TABLE messages CHANGE `from` sender VARCHAR(100);
ALTER TABLE messages CHANGE `to` recipient VARCHAR(100);

Better: stop building SQL by concatenating variables and use prepared statements so quotes inside values cannot break the query and you avoid SQL injection. A minimal PDO example:

$stmt = $pdo->prepare("INSERT INTO messages (sender, recipient, subject, body) VALUES (?, ?, ?, ?)");
$stmt->execute([$from, $to, $sub, $body]);

Quick troubleshooting checklist:

  • Confirm the column list and the VALUES list have the same number of items and the order matches.
  • If you keep reserved-word column names, always quote identifiers in SQL for MySQL (backticks).
  • Check the exact error text from MySQL (use mysqli_error or catch PDOException) — it often points to the offending token.
  • Use parameterized queries instead of manual escaping; if escaping is needed, use the API escape functions.

For the definitive list of reserved words and identifier rules, see the MySQL manual: MySQL Keywords and Reserved Words.

Recommended Answers

All 4 Replies

Try:

insert into messages (`from`,`to`,`subject`,`body`) values ('$from','$to','$sub','$body')

If you still have errors, than there could be unescaped quotes in the subject or body.

^Will you please tell what is the need of using back-ticks? I always use insert statements without these, and haven't encountered any problem as yet.

"from" is also a reserved word (SELECT * FROM). The backticks are used to specify explicitly it is a column name.

"from" is also a reserved word (SELECT * FROM). The backticks are used to specify explicitly it is a column name.

Thanks. In fact, MySQL isn't allowing creation of table with field FROM.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.