1

For hours now, am trying to query multiple database records and then insert into database using nodejs. The problem is that it only insert one rows per call instead of looping and inserting all database rows at once. can someone help me fix the issue.

con.query("SELECT * FROM users", function (err, result, fields) {


if (err) throw err;
    console.log(result);



//You just insert a nested array of elements.

  var sql = "INSERT INTO customers (name, address) VALUES ?";
  var values = [[result[0].username], result[0].id]];

  con.query(sql, [values], function (err, result) {
    if (err) throw err;
    console.log(" Number of records inserted: " + result.affectedRows);
  });



  });

1 Answer 1

3

Try this :)

con.query("SELECT * FROM users", function (err, result, fields) {
    if (err) throw err;
    console.log(result);
    if(result && result.length>0) {
        var sql = "INSERT INTO customers (name, address) VALUES ?";
        var values = [];
        for (var i = 0; i < result.length; i++) {
            values.push([result[i].username, result[i].id]);
        }
        con.query(sql, [values], function (err, result) {
            if (err) throw err;
            console.log(" Number of records inserted: " + result.affectedRows);
        });
    }
    else{
        console.log("No data found")
    }
});
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.