0

So I've been using node.js and mysql for a while now but I've run into a new issue. I know I made the title seem basic but I just have no idea how I can title this question. So let's say I have:

connection.query(SELECT column FROM table, function(err, result) {
  if (err) {
    console.log(err)
  }
  if (result.length > 0) {
    console.log(result[0].thisNeedsToBeAVar)
  }
})

now in most cases, I would just use result[0].column and it's all good. But the entire issue is that column could be anything in my case. So I have that column as a var. How do I use it when I log the result? If I simply put the var there, it thinks that the column's name is literally whatever the var is called...

t.niese
  • 39,256
  • 9
  • 74
  • 101
APixel Visuals
  • 89
  • 1
  • 1
  • 12

1 Answers1

-1

If var a = {b : 'hello'}; then we can access b as a.b as well as a[b].

    var column = ''; // any column name
    connection.query('SELECT ' + column + ' FROM table', function (err, result) {
    if (err) {
    console.log(err)
              }
    if (result.length > 0) {
    console.log(result[0][column])
            }
       })
  • This won't work, because there is no space before and after `' + column + '`. Beside that it is a really bad idea inject an identifier without escaping. And you should explain your answer, and not only post some code. – t.niese Oct 17 '17 at 04:32