VladGershun
VladGershun

Reputation: 27

How to save information from an SQL query to a variable

I'm trying to save the information I get from my inmatefirst column with my SQL query into the variable "first'. I was wondering what the correct syntax/approach was to doing this.

let sql = `SELECT * FROM inmates WHERE inmatefirst = ? AND inmatelast = ? AND dob = ?`;
let query = db.query(sql, [search.first, search.last, search.dob], (err, result) => {
  if (err) throw err;
  if (result.length != 0) {
    res.render(path.resolve('./myviews/modify'), {
      good: 'Person Found - Please Enter Updated Information',
      first: result.inmatefirst,
      last: result.last,
      dob: result.dob,
      sex: result.sex

    });
  });
});

Upvotes: 0

Views: 778

Answers (1)

O. Jones
O. Jones

Reputation: 108706

Your SQL says, in part, this:

SELECT * FROM inmates WHERE inma...

You've asked for every column from the table. That can make life confusing.

Instead, spell out the columns you want. Your Javascript indicates that you want these ones:

SELECT inmatefirst, last, dob, sex FROM inmates WHERE inma...

(It's possible that is the wrong set of columns. Check it.

Then, as @barmar pointed out, use result[0].first etc, because result is an array of objects, one for each row of your resultset.

Upvotes: 1

Related Questions