How to use Mysql’s SELECT + WHERE dynamically?

Asked

Viewed 81 times

1

I need to search the Mysql database, however I may have one or more filters (maximum 6) in the WHERE clause.

Example:

SELECT * FROM 'table_name'
WHERE coluna_1 = 'valor_1'

or

SELECT * FROM 'table_name'
WHERE 
     coluna_1 = 'valor_1' AND
     coluna_2 = 'valor_2' AND
     .
     .
     .
     coluna_6 = 'valor_6'

I can save the column name information and the value to be searched for in a variable and then pass in WHERE?

let searchBy = `${coluna_1} = ${valor_1} AND ${coluna_2} = ${valor_2}`

SELECT * FROM 'table_name'
WHERE ${searchBy};
  • Which customer are you using? It’s the mysql? If you interpolate the values literally like this you run great risk of SQL Injection, which is extremely serious. Do not forget to [Edit] your question to include this information.

No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.