Update mysql database with array condition Code Answer

Hello Developer, Hope you guys are doing great. Today at Tutorial Guruji Official website, we are sharing the answer of Update mysql database with array condition without wasting too much if your time.

The question is published on by Tutorial Guruji team.

I have an array of unique Ids like the following one:

const myIds = [2, 3, 4];

I also have a database like this one:

+-----+------+
| id  | seen |
+-----+------+
|   0 |    0 |
|   1 |    0 |
|   2 |    0 |
|   3 |    0 |
|   4 |    0 |
+------------+

I would like to update my database so that the seen column of all the ids in my array are set to 1. That would leave me with this:

+-----+------+
| id  | seen |
+-----+------+
|   0 |    0 |
|   1 |    0 |
|   2 |    1 |
|   3 |    1 |
|   4 |    1 |
+------------+

I have tried this code but it only updates one entry:

    db.query('UPDATE table SET seen = 1 WHERE id = ?', myIds,
    function (error, results) {
        if (error) throw error;
        console.log("ok");
    });

Is there any other way to do so ?

Thanks for your help.

Answer

Thanks @cdaiga I managed to make it work:

db.query('UPDATE table SET seen = 1 WHERE id IN (?)', [myIds],
    function (error, results, fields) {
        if (error) throw error;
        console.log("ok");
});
We are here to answer your question about Update mysql database with array condition - If you find the proper solution, please don't forgot to share this with your team members.

Related Posts

Tutorial Guruji