简体   繁体   中英

how to replace all the single quotes to \' for a mysql query

I have made a simple query using nodejs and mysql. The issue is whenever the user inputs product details containing any single quote an error occurs. How do i replace or remove such error.

node-mysql这是一个很好的库,它可以自动转义查询值并将其检出https://github.com/mysqljs/mysql#escaping-query-values

For my understanding you want to Escaping query values when you perform the mysql operations i don't know which mysql driver you are using but i will suggest some solutions with node.js driver for mysql.

On this nodejs mysql drive builtin mechanism for Escaping query values.In order to avoid SQL Injection attacks, you should always escape any user provided data before using it inside a SQL query. You can do so using the mysql.escape() , connection.escape() or pool.escape() methods:

Caution These methods of escaping values only works when the NO_BACKSLASH_ESCAPES SQL mode is disabled (which is the default state for MySQL servers).

var userId = 'some user provided value';
var sql    = 'SELECT * FROM users WHERE id = ' + connection.escape(userId);
connection.query(sql, function (error, results, fields) {
  if (error) throw error;
  // ...
});

Alternatively, you can use ? characters as placeholders for values you would like to have escaped like this:

connection.query('SELECT * FROM users WHERE id = ?', [userId], function (error, results, fields) {
  if (error) throw error;
  // ...
});

Multiple placeholders are mapped to values in the same order as passed. For example, in the following query foo equals a, bar equals b, baz equals c, and id will be userId :

connection.query('UPDATE users SET foo = ?, bar = ?, baz = ? WHERE id = ?', ['a', 'b', 'c', userId], function (error, results, fields) {
  if (error) throw error;
  // ...
});

This looks similar to prepared statements in MySQL, however it really just uses the same connection.escape() method internally.I hope this will helps you.

您必须使用escape函数对mysql文档中针对nodejs的输入值进行escape

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM