Last active
July 29, 2021 07:24
-
-
Save Zei33/0b96fda3c8c38f45c5c81c13a45fc408 to your computer and use it in GitHub Desktop.
Build a mysql search query with unknown number parameters (Javascript)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var query = "hello world "; | |
// Split query string and filter out empty words. | |
var queryWords = query.split(' ').filter(x => x.length); | |
console.log(queryWords); | |
// ["hello", "world"] | |
// Create WHERE clause that matches all words in the search (works for a single word too). | |
const match = `(${queryWords.map((x) => "TableName.Column LIKE '%?%'").join(' AND ')})`; | |
console.log(match); | |
// "(TableName.Column LIKE '%?%' AND TableName.Column LIKE '%?%')" | |
var exampleID = 100; | |
var exampleString = "john"; | |
// Use the spread operator to insert the queryWords array and flatten it. | |
var parameters = [exampleID, exampleString, ...queryWords]; | |
// [100, "john", "hello", "world"] | |
// Insert the search string into your WHERE clause and the flattened parameters to bind. | |
connection.promise().query(` | |
SELECT | |
* | |
FROM | |
TableName | |
LEFT JOIN Table2Name | |
ON TableName.Column2 = Table2Name.Column AND Table2Name.Column2 = ? | |
WHERE | |
TableName.Column3 = ? OR | |
${match} | |
`, parameters) | |
.catch((error) => console.log(`ERROR: ${error}`)); | |
// Now a shorter way of writing this code. | |
var searchQuery = (q, c, t = "AND") => { | |
const qw = q.split(' ').filter(x => x.length).map(x => `%${x}%`); | |
return [`(${qw.map((x) => `${c} LIKE ?`).join(` ${t} `)})`, qw]; | |
}; | |
var [match, parameters] = searchQuery("hello world I'm here", "TableName.Column"); | |
connection.promise().query(` | |
SELECT | |
* | |
FROM | |
TableName | |
WHERE | |
TableName.Column2 LIKE ? OR | |
${match} OR | |
TableName.Column4 = ? | |
`, ["john", ...parameters, 100]) | |
.catch((error) => console.log(`ERROR: ${error}`)); | |
// One final note, on the offchance that you need to use OR instead of AND, the third parameter can be changed. | |
// searchQuery(query, "OR"); | |
// otherwise, you can ignore the third parameter. | |
// Hope you find this useful | |
// - Matthew Scott |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment