Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Reducing a certain amount from everyone's data in MySQL

I have a MySQL database. I want to reduce certain data using Cronjob at certain times of the week.

(Table name: Accounts)

username | hunger | hp
         |        |
Dworczyk | 100    | 100
Mateusz  | 100    | 95 

Let’s say a random amount will be reduced from the hunger data of everyone in the table above. In other words, the hunger data of all the people above will be reduced.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

const CronJob = require('cron').CronJob;
const { con, pool } = require("./container/mysql.js")

let random_number = Math.floor(Math.random() * 100) + 1;

let job = new CronJob('0 0 * * *', function() {
    pool.query(`SELECT * FROM Accounts WHERE username = 'Dworczyk'`, async (err, rows) => {
        if (err) throw err;
        pool.query(`UPDATE Accounts SET hunger = ${rows[0].hunger} - ${random_number}`);
    });
}, null, true, 'America/Los_Angeles');

job.start();

What I did above is simple subtraction from a single person. It shouldn’t just be tied to "Dworczyk". How can I make transactions on everyone without using the WHERE key?

>Solution :

Subtract from the column itself rather than a variable.

Also, use parametrized queries rather than substituting variables into the SQL.

pool.query('UPDATE Accounts SET hunger = hunger - ?', [random_number], function(err, response) {
    if (err) throw err;
});
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading