6

Currently, in node.js, if I want to search for a string in multiple columns in a MySQL table I have to do like this:

mysqlConnection.query(
    "SELECT * FROM my_table WHERE column_a LIKE ? OR column_b LIKE ? OR column_c LIKE ?",
    [searchString, searchString, searchString],
    callback
);

I want to be able to do it like this:

mysqlConnection.query(
    "SELECT * FROM my_table WHERE column_a LIKE ? OR column_b LIKE ? OR column_c LIKE ?", 
    searchString, callback
);

Or maybe even with named parameters:

mysqlConnection.query(
    "SELECT * FROM my_table WHERE column_a LIKE :searchString OR column_b LIKE :searchString OR column_c LIKE :searchString",
    {searchString: "needle"},
    callback
);

Is there a way I can do it?

3
  • 2
    github.com/mysqljs/mysql#custom-format Commented Apr 8, 2017 at 13:48
  • @robertklep Well, that's pretty much what I'm looking for... but I don't think I should be trusted to prepare the statement myself. I might end up poking holes in the security. Commented Apr 8, 2017 at 14:15
  • Well, the code that I linked to is provided by the developer of mysql, and AFAICS it's exactly what you want :) Commented Apr 8, 2017 at 14:16

1 Answer 1

3

you can enable named parameter when creating your db pool connection.

const connection = mysql.createPool({
  ...yourConfig,
  namedPlaceholders: true,
});

edit: As @robertklep explained it only works on mysql2 npm package

Sign up to request clarification or add additional context in comments.

1 Comment

To be clear: that will work with mysql2, not with mysql.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.