1

I am doing an application with Node js, Express and MySQL. I am running on localhost with XAMPP, not sure if this information is important. I want to insert multiple rows in my database, so I did:

    db.query('INSERT INTO tasks (done, user_id, task) VALUES ?', values, (err, result) => {
            if(err) {
                console.log(err);
            } 
            console.log("done");

        });

where values is an array of arrays containing each a triplet (done, user_id, task), example [[0, 10, 'foo'], [1, 10, 'bar']]. However, when this snippet runs with more than one array in values it gives me an error like

Error: ER_PARSE_ERROR: You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near '0, 10, 'test'' at line 1

What am I doing wrong? Is there another way to insert multiple rows?

** EDIT: ** My problem is multiple row insertion, I know that the generated query has the wrong syntax, but according to this accepted answer my Javascript syntax sould be correct

2 Answers 2

1

As it is stated in the mentioned answer, your values should be wrapped in another brackets [values]

Note: values is an array of arrays wrapped in an array

Sign up to request clarification or add additional context in comments.

3 Comments

The problem is with multiple insertion, my javascript syntax was taken by this accepted answer, maybe I have to edit and clarify the question
I see, in that example they have array of array too, but they wrap it in another one by [values] as the query parameter so it becomes "an array of arrays wrapped in an array" as stated in that answer. Did you tried it that way?
Oh, I didn't notice it, now it works! Edit the answer with this information, I'll mark as accepted
0

I don't know variable "values" look like, but you need check syntax.

right syntax is : INSERT INTO tbl_name (a,b,c) VALUES(1,2,3),(4,5,6),(7,8,9);

2 Comments

values is for example [[0, 10, 'foo'], [1, 10, 'bar']]. I can't replace values one by one because I don't know how many do I have to insert every time. According to this accepted answer my Javascript syntax is correct for multiple row insertion, but it actually messes up SQL syntax
you need convert [[0, 10, 'foo'], [1, 10, 'bar']] to (0, 10, 'foo'), (1, 10, 'bar')

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.