1

My query is:

connection.query("SELECT * FROM posts WHERE someId = 2", (err, rows) => {

    allIds = [];

            for(var i = 1; i <= rows.length; i++){
                allIds.push(rows.id_post)
            }

             res.send("The IDs : " + allIds )
});

rows.length = 5, I'm getting the response: The IDs : , , , , ,. There is no data. I need all the IDs listed. Later want to run another query with those Ids, maybe in the same query but for now why aren't the IDs showing? What am I missing?

Somename
  • 3,376
  • 16
  • 42
  • 84

2 Answers2

1

It seems like 'rows.id_post' is undefined. Are you sure there is a property named 'id_post'? Is rows a json or an array? If it's an array you need:

for(var i = 0; i < rows.length; i++){
        allIds.push(rows[i].id_post)
    }

This should answer your question.

jetblack
  • 155
  • 7
  • Thanks. So what's causing `i<=rows.length` to fail and `<` to pass? Did that or `i=0` is resolving this? – Somename Sep 19 '17 at 13:22
  • 1
    arrays are 0 indexed. so the object array[array.lenght] doesn't exist. – jetblack Sep 19 '17 at 13:24
  • Can you help me with https://stackoverflow.com/questions/46302496/recursive-query-issue-with-mysql please. Same query extended. – Somename Sep 19 '17 at 14:01
0
for(var i = 1; i <= rows.length; i++){
            allIds.push(rows.id_post)
        }

You're not referencing the index of the rows results... I'm not familiar with the Node.JS syntax but I would think you need to reference the i row to get the value to push...

  • You mean `allIds.push(rows[i].id_post)`? I tried that and get error : `TypeError: Cannot read property 'id_comment' of undefined` – Somename Sep 19 '17 at 13:12
  • try this: connection.query("SELECT * FROM posts WHERE someId = 2", function selectAll(err, rows, fields) { – Daniel Sampson Sep 19 '17 at 13:19