简体   繁体   中英

Using a variable in a WHERE clause MySQL/Node

I'm trying to make a MySQL query to filter data from a table. Effectively what I want to do is:

SELECT data FROM table WHERE column IN?

The filter is coming from checkboxes in a form on a webpage, so I can pass an array or object fairly easily, but it'll be a varying number of parameters for the IN each time, so I can't us multiple?. I tried making a for loop to make multiple queries concatenate the arrays that the queries returned, but I ran into scope issues with that. I also tried passing an array directly to the query, but that throws a syntax error. I'm sure there's a straightforward answer to this but I'm not sure how to do it.

Edit: source code added:

Here's where I'm at:

const filterShowQuery = `SELECT sl_Show.showId, sl_Band.BandName,
      sl_Show.date, sl_Venue.venueName,
      sl_Show.length, sl_Show.attendance, sl_Show.encore FROM sl_Show 
      JOIN sl_Band on sl_Show.BandID = sl_Band.BandId
      JOIN sl_Venue on sl_Show.VenueId = sl_Venue.VenueId
      WHERE sl_Band.BandName IN (?)
      ORDER BY sl_Band.BandName;`;

Trying to get an array into the? in WHERE sl_Band.BandName IN

const getShows = (req, res,next) =>{
  var {bands, venues} = req.body;
  var i = 0;  //left over from previous attempt
  var data = [];
  for (b in bands){
    mysql.pool.query(filterShowQuery, bands[b], (err, result) => {
      if(err){
        console.log('filter band error');
        next(err);
        return;
      }

    data = data.concat(result);
    console.log(data); //data concatenates property and increases through for loop
    })
// same action to be performed with venues once solved
//  for (v in venues){
//    conditions[i] = venues[v];
//  i++;
    console.log(data);  //data is empty when logging from here or using in res
    res.json({rows:data});
  }
}

SECURITY WARNING!

I must to say: NEVER, NEVER PASS DATA DIRECTLY TO YOUR SQL!

If you don't know why, just google for SQL Injection . There are lots of examples on how it is done, how easily it can be done, and how to protect your application from this sort of attack.

You should always parametrize your queries. But in the very rare case which you really need to insert data concatenating a string into your sql, validate it before.
(Eg) If it's a number, than use a Regex or some helper method to check if the value you are inserting into your SQL String is really and only a number and nothing else.

But aside that, you did not provide any source code, so it's really hard to give any help before you do that.

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