Languages

Node.js - MySQL - ER_PARSE_ERROR with placeholders

0 points
Asked by:
Waleed-Gates
322

I was trying to select records in my database (MySQL), but I got this response:

  code: 'ER_PARSE_ERROR',
  errno: 1064,
  sqlMessage: "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 ''users' ORDER BY 'name'' at lin
' at line 1",
  sqlState: '42000',
  index: 0,
  sql: "SELECT * FROM 'users' ORDER BY 'name'

My code: 

con.connect((err) => {
  if (err) throw err;
  let sql = `SELECT * FROM ? ORDER BY ?`;
  const values = ['users', 'name'];

  // sends queries and receives results
  con.query(sql, values, (err, result) => {
    if (err) throw err;
    console.log(result);
    con.end();
  });
});

How to fix this?

1 answer
0 points
Answered by:
Waleed-Gates
322

SQL syntax does not tolerate single quotes for table and column names.

Correct SQL syntax:

  1. SELECT * FROM users ORDER BY name
  2. SELECT * FROM `users` ORDER BY `name` - with backticks

To enter the values you want using placeholders, use ?? instead of ?

? is for ordinary values, ?? is used for column and table names.

Fixed code: 

con.connect((err) => {
  if (err) throw err;
  let sql = `SELECT * FROM ?? ORDER BY ??`;
  const values = ['users', 'name'];

  // sends queries and receives results
  con.query(sql, values, (err, result) => {
    if (err) throw err;
    console.log(result);
    con.end();
  });
});
0 comments Add comment
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join