0

I am trying to insert several records in a mysql database and I need to get each record's ID and send it back to the client. The code I'm using:

app.post('/saveLesson',function(req, res){

    var idArray = [];

    let sections = JSON.parse(req.body.sections);

    for (let i = 0; i < sections.length; i++) {

        let sql = 'INSERT INTO sections (title, content, duration) VALUES ("' + sections[i].title + '","' + sections[i].content + '","' + sections[i].duration + '");';

        connection.query(sql,
            function (error, result) {
                if (error) throw error;
                idArray.push(result.insertId);
                console.log('array in the loop: ' + idArray);
            }
        );
    }

    console.log('array out of the loop: ' + idArray);
    res.send(idArray);

});

The problem is that the .query method seems to be asynchronous and the following code is executed before the idArray is actually populated:

    console.log('array out of the loop: ' + idArray);
    res.send(idArray);

What would be the appropriate way to deal with this issue?

devamat
  • 2,293
  • 6
  • 27
  • 50
  • 3
    Possible duplicate of [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – NullDev May 27 '19 at 08:18
  • i see several problems with this code. First of all SQL injection right in there. Second the looping db connection which causes unessasry DB connection on server. You should generate one qyery for all inserts return ids using either async/await, promise, callback, and use parameter in your query instead of directly putting data inside query – Maielo May 27 '19 at 08:45
  • Thank you for your post. This code is just "temporary", I'm just trying to build a structure. Previously I added all records with a sigle query but doing so how can I get every new id? – devamat May 27 '19 at 08:49

0 Answers0