0

I use Node.js and i want to INSERT few value in my table.

like:

id | profile_id | user_id 
1  |     2      |     7
2  |     2      |     3
3  |     2      |     4 
4  |     2      |     6 

i have an array (user_id) with all my date(ids), i have to do a foreach in my array for insert each user_id value like

foreach...
connection.query('INSERT INTO mytable SET ?', my_obj, function(error,risultato) { ...

or i can do a cycle inside mysql with one statement?

2 Answers 2

2

You can use the following syntax for multiple insterts in MySQL:

INSERT INTO mytable (id, profile_id, user_id) VALUES(?,?,?),(?,?,?),(?,?,?);

Therefore yor code would be:

 connection.query("INSERT INTO mytable (id, profile_id, user_id) VALUES(?,?,?),(?,?,?),(?,?,?)", 
    [id1, profile_id1, user_id1, id2, profile_id2, user_id2, id3, profile_id3, user_id3], 
    function(err, result){ .... });
Sign up to request clarification or add additional context in comments.

2 Comments

i have to do a foreach for to have profile_id1 profile_id2 profile_id3 before INSERT INTO
You don't need foreach for query. You may need it to prepare your array [id1, profile_id1, user_id1.....
1

After answer @Mustafa i do it: (use sugar.js and felixge/node-mysql)

var place ="(";
rows.each(function(n) {
    columns.add(n.profile_id);
    columns.add(n.user_id);
    columns.add(new Date());
    place += '(?,?,?),';
});


place= place.slice(0,place.lastIndexOf(","));

var sql = 'INSERT INTO mytable (profile_id,user_id,created) VALUES '+place+' ON DUPLICATE KEY UPDATE id=id';

connection.query(sql,
    columns
    , function(error, rows) {
        if (error) {
            var err = "Error on " + error;
            console.dir(err);
            console.log('>>>>>ERROR<<<<< ' + err);
            throw err;
        }

        connection.release();
        callback(rows);

I hope to help someone

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.