Home > Enterprise >  mysql update in nodejs
mysql update in nodejs

Time:10-19

I have written the code to upate the creditAmt and use that same creditAmt to increment the accountBal field.

Here is the code that I have tried:

router.put('/', (req, res) = >{
  const {
    accountBal
  } = req.body;
  conn.query('UPDATE accounts SET creditAmt=accountBal WHERE accNum=?', (errors, resul) = >{
    if (errors) {
      return console.log(errors);
    } else {
      return res.send('Account credited');
    }
  });
})

CodePudding user response:

You Need To Check In Line Number 22 Here I Have Write Program To Do This Simple Task

// Update Account Balance // This script will update the account balance for a given account

router.put('/', (req, res) => {
    const { custId, accNum, narr, creditAmt } = req.body;
    conn.query('SELECT accNum FROM accounts WHERE accNum = ?', [accNum], (error, results) => {
        if (error) {
            return console.log(error);
        }
        if (results.length > 0) {
            res.send(results);
        }
        conn.query('INSERT INTO accounts SET ?', { custId: custId, accNum: accNum, narr: narr, creditAmt: creditAmt }, (err, accR) => {
            if (err) {
                return console.log(err);
            }
            const {accountBal}=req.body;
            conn.query('UPDATE accounts SET creditAmt=accountBal WHERE accNum=?', (errors, resul) => {
                if (errors) {
                    return console.log(errors);
                } else {
                    var updateBalance = accountBal   creditAmt;
                    conn.query('UPDATE accounts SET accountBal=? WHERE accNum=?', [updateBalance, accNum], (err, result) => {
                        if (err) {
                            return console.log(err);
                        } else {
                            return res.send('Account credited');
                        }
                });
            }
            });
        });
    });
})

CodePudding user response:

You need to pass the parameters to the query:

router.put('/', (req, res) => {
  const { accountBal } = req.body;
  conn.query(
    'UPDATE accounts SET creditAmt = ? WHERE accNum = ?',
    [accountBal, <account-number>], // You will also need to provide the accNum
    (errors, resul) => {
      if (errors) {
        return console.log(errors);
      } else {
        return res.send('Account credited');
      }
    }
  );
});
  • Related