Hey folks! I’m struggling with a MySQL update. I want to change several records at once using one query. I’m using a Promise-based class for my database operations but it’s not working as expected.
Here’s what I’ve got:
// API endpoint
app.post('/confirm', (req, data) => {
const db = new DBManager(dbConfig);
const updateSql = 'UPDATE `unconfirmed_data` SET `source` = ? WHERE `item_id` = ?';
const itemData = [req.body[0].source, req.body[0].item_id];
db.startOperation([updateSql], itemData)
.then(result => console.log(result))
.catch(err => console.log(err));
data.send('Changes applied');
});
// DBManager class
class DBManager {
constructor(config) {
this.conn = mysql.createConnection(config);
}
runQuery(sql, args) {
return new Promise((resolve, reject) => {
this.conn.query(sql, args ? [args] : null, (err, output) => {
if (err) reject(err);
else resolve(output);
});
});
}
startOperation(sqlList, args) {
return new Promise((resolve, reject) => {
this.conn.beginTransaction(err => {
if (err) reject(err);
// More code here...
});
});
}
}
I’m getting a syntax error. Any ideas what I’m doing wrong? Thanks!
This approach will update all specified records in one go. Make sure to validate and sanitize your inputs to prevent SQL injection attacks. If you need to update with different sources for each item, you might want to use a transaction with multiple individual updates instead.
This should update all specified records in one go. Remember to properly sanitize inputs to prevent SQL injection.
If you need different sources for each item, you might want to use a transaction with multiple individual updates instead. Let me know if you need help with that approach.
hey mia92, i think i see ur problem. ur trying to update multiple records but ur query is set up for just one. try using the IN operator in ur SQL like this:
UPDATE unconfirmed_data SET source = ? WHERE item_id IN (?)
then pass an array of item_ids as the second argument. that should do the trick!