Increment a value on MYSQL with react node.js - mysql

Why does this doesn't work
const increment = 'votes + 1'
db.query("UPDATE president SET votes = ? WHERE nickname = ?",
[increment, president], (err, result) => {
if (err) {
console.log(err)
} else {
console.log(result)
}
})
but this code below works
db.query("UPDATE president SET votes = votes + 1 WHERE nickname = ?",
[president], (err, result) => {
if (err) {
console.log(err)
} else {
console.log(result)
}
})
I just want to do the incrementing of mysql columns with votes = ?
I wanted to do it with the votes = ? way. Does anyone know the proper syntax of incrementing a value in mysql with react node js?

Related

How to eliminate all queries if one failed

app.post('/transfer', (req,res) => {
db.query('SELECT * FROM bank.user_info where acc_no = ?',
[req.body.from],(err, result) => {
if(err){
res.send({err: err,id: 0});
}else{
if(req.body.Amount>result[0].acc_bal){
res.send({err: "Insufficient Balance !!!",id: 1})
return 0;
}else{
const senderNew = {};
senderNew.amount = req.body.Amount;
senderNew.transaction = 'sent';
senderOld.push(senderNew);
const freshSend = JSON.stringify(senderOld);
const senderBal = result[0].acc_bal-req.body.Amount;
db.query('UPDATE user_info SET transactions = ?, acc_bal = ? WHERE acc_no = ?',
[freshSend, senderBal, req.body.from], (err,result) => {
if(err){
res.send({err: err,id: 2})
}else{
db.query('SELECT * from user_info WHERE acc_no = ?',
[req.body.to], (err, result) => {
if(err){
res.send({err: err,id: 3});
}else{
const receiverOld = JSON.parse(result[0].transactions);
const receiverNew = {};
receiverNew.amount = req.body.Amount;
receiverNew.transaction = 'received';
receiverOld.push(receiverNew);
const freshReceive = JSON.stringify(receiverOld);
const receiverBal = parseInt(result[0].acc_bal) + req.body.Amount;
db.query('UPDATE user_info SET transactions = ?, acc_bal = ? WHERE acc_no = ?',
[freshReceive, receiverBal, req.body.to], (err, result) => {
if(err){
res.send({err: err,id: 4});
}else{
db.query('SELECT * FROM user_info WHERE acc_no = ?',
[req.body.from], (err, final) => {
if(err){
res.send({err: err, id: 5});
}else{
res.send(final);
console.log(final);
}
})
}
})
}
})
}
})
}
}
})
});
Now in this code, if the initial block fails, the others don't execute but if the last ones fail, the initial block still gets passed, how can I improve the code so that if any query fails, the ithers fail too...
I've checked this but it didn't helped as I need a Node.js tutorial
How to stop all DB queries if one fails

Getting a function out of a query

I'm trying to get a variable out of a query as shown below, thanks in advance
var deutsch_meund_note = "";
connection.query(
'SELECT count(*) as sum FROM noten WHERE id = ? and fach = ?',
[id, "mathe"],
function(error, results, fields) {
if (error) {
console.log("no deutsch_schr for id: "+ id);
} else {
const deutsch_meund_viel = results[0].sum;
connection.query(
'SELECT SUM(note) as sum FROM noten WHERE id = ? and fach = ?',
[id, "deutsch_meund"],
function(error, results, fields) {
const deutsch_meund_insge = results[0].sum;
const deutsch_meund_note = deutsch_meund_insge / deutsch_meund_viel;
//this variable: **var deutsch_meund_note = deutsch_meund_note;**
});
}
});
I need to get the variable out of the "connection.query" function but when I try it like the example above it just says "undefined"

Failed to Update MySQL table using Express JS

I am facing difficulties to update the following tables (MySQL) by using Express Js.
productdb.discount
discount_id | discount_name | discount_percent
productdb.product
product_id | discount_id | product_price(original price) | product_latest_price(price after discount) |
It works on this way :
User update the existing discount table by inserting new discount name, percent and select relevant product that applies the respective discount from the checkbox. The input form is as below:
Hence when submit, it will return the discount info, including the discount_id, and the selected product in array-form according to the assigned product_id.
My concept of updating the database table is :
First, Update the discount table.
Then, Update all discount_id in product table to null according to the discount_id.
Update the product latest price to product price.
Update the discount_id to the product table according to the submitted product array.
Finally, Update the product_latest_price by calculating the result after multiple with discount_percent.
I wrote the Query in Express Promise based and it doesn't execute correctly as it failed to update the product_latest_price(Possibly due to async method). In fact, the code looks messy. Anyone have any idea on updating these tables in a more efficient way, or much cleaner code?
By the way, my code to execute the query is as below.
exports.discount_update = (discount_info, discount_id, product_id) => {
return new Promise((resolve, reject) => {
connectionPool.getConnection((connectionError, connection) => {
if (connectionError) {
reject(connectionError);
} else {
connection.query(`UPDATE productdb.discount SET ?
WHERE discount_id = ?`, [discount_info, discount_id], (error, result) => {
if (error) {
reject(error);
} else {
connection.query(`UPDATE productdb.product
SET discount_id = null, product_latest_price = product_price
WHERE discount_id = ?`, [discount_id], (error, result) => {
if (error) {
reject(error);
} else if (result.affectedRows >= 1) {
for (i = 0; i < product_id.length; i++) {
connection.query(`UPDATE productdb.product
SET discount_id = ?
WHERE product_id = ?`, [discount_id, product_id[i]], (error, results) => {
if (error) {
reject(error);
} else {
connection.query(`UPDATE productdb.product AS product
JOIN productdb.discount AS discount
ON product.discount_id = discount.discount_id
SET product.product_latest_price = product.product_price - product.product_price * (discount.discount_percent) / 100
WHERE product_id = ?`, [product_id[i]], (error, result) => {
if (error) {
reject(error);
} else if (result.affectedRows >= 1) {
resolve(result)
} else {
resolve(result)
}
})
}
})
}
}
})
}
})
}
})
})
}

My Sql query return an empty array with req.params.id in nodejs

I have i Mysql query with nodejs like this :
application.get('/Modification/:idt',function(req,res){
connection.query("SELECT * FROM memos WHERE idMemo = 'req.params.idt'",function (error, rows){
if (error) {
console.log("error ocurred",error);
}
else {
console.log(req.params.idt);
console.log(rows);
var no = rows;
res.render('memosModif.ejs', {no});
}
});
});
and my query return an empty array even if req.params.idt return an int value like 1 or 2 ... , but when i replace req.params.id with a int like 1 or 2 ... the query returns the right result
i dont understand why and how to fix that .
You are comparing the idMemo column to the string literal 'req.params.idt'. Instead, you should bind the value from this variable:
connection.query("SELECT * FROM memos WHERE idMemo = ?", req.params.idt, function (error, rows) {

Mysql, Node, query within a query, how to populate property in map function from another query

Firstly, if anyone can edit my question title or question to make more sense, please do.
I have a node/express app making mysql queries with mysql.js. I have a query that looks up a table of questions and then runs a map function on the results. Within that map function, I need to query another table, of answers, corresponding to each record in the questions table. The value I need is the number of answers to that question, ie the number of records in each answers table. I've tried all kinds of different examples, but nothing quite fits my case in a way that makes sense to me. New at Node and Express, and even MySQL so having a hard time picking out quite what to.
I understand that the problem is the async nature of node. getAnswersCount() returns "count" before the query finishes. Below is my code. Need some advice on how to achieve this.
The value 123 is assigned to count just to clarify the trace results.
app.get('/', (req, res) => {
db.query('SELECT * FROM questions LIMIT 0, 100',
(error, results) => {
if (error) throw error;
questions = results.map(q => ({
id: q.id,
title: q.title,
description: q.description,
answers: getAnswersCount( q.id )
}));
res.send( questions );
});
});
const getAnswersCount = ( id ) =>
{
const tableName = 'answers_' + id;
var count = 123;
var sql = `CREATE TABLE IF NOT EXISTS ${tableName}(
id int primary key not null,
answer varchar(250) not null
)`;
db.query( sql,
(error, results) => {
if (error) throw error;
//console.log( 'answers table created!' );
});
sql = `SELECT COUNT(*) AS answersCount FROM ${tableName}`;
db.query( sql,
(error, results) => {
if (error) throw error;
//console.log( count ); // will=123
count = results[0].answersCount;
//console.log( count ); // will = results[0].answerCount
});
// I know this code runs before the query finishes, so what to do?
//console.log( count ); //still 123 instead of results[0].answersCount
return count;
}
EDIT: After attempting various versions of Michael Platt's suggestion in his answer without success, I finally worked out a solution using Express callbacks and a promise, adding the answers values to the questions array afterwards:
app.get( '/', (req, res, next ) => {
db.query('SELECT * FROM questions LIMIT 0, 100',
(error, results) => {
if (error) throw error;
questions = results.map(q => ({
id: q.id,
title: q.title,
description: q.description,
}));
next();
});
}, (req, res ) => {
questions.map( currentElem => {
getAnswersCount( currentElem.id ).then( rowData => {
currentElem.answers = rowData[0].answersCount;
if( currentElem.id == questions.length ) res.send( questions );
});
});
});
const getAnswersCount = ( id ) => {
const tableName = 'answers_' + id;
var sql = `CREATE TABLE IF NOT EXISTS ${tableName}(
id int primary key not null,
answer varchar(250) not null
)`;
db.query( sql,
(error, results) => {
if (error) throw error;
//console.log( 'answers table created!' );
});
sql = `SELECT COUNT(*) AS answersCount FROM ${tableName}`;
return new Promise( ( resolve, reject ) => {
db.query( sql, ( error, results ) => {
if ( error ) return reject( err );
resolve( results );
});
});
}
I'm not sure which database module you are using to connect to and query the database but you could make the method async and then await the response from the query like so:
const getAnswersCount = async ( id ) =>
{
const tableName = 'answers_' + id;
var count = 123;
var sql = `CREATE TABLE IF NOT EXISTS ${tableName}(
id int primary key not null,
answer varchar(250) not null
)`;
var results = await db.query(sql);
sql = `SELECT COUNT(*) AS answersCount FROM ${tableName}`;
var count = db.query(sql)[0].answerCount;
// I know this code runs before the query finishes, so what to do?
//console.log( count ); //still 123 instead of results[0].answersCount
return count;
}
app.get('/', async (req, res) => {
db.query('SELECT * FROM questions LIMIT 0, 100',
(error, results) => {
if (error) throw error;
questions = results.map(q => {
const answerCount = await getAnswersCount( q.id )
return {
id: q.id,
title: q.title,
description: q.description,
answers: answerCount
}
}));
res.send( questions );
});
});
I think that will give you what you want and run correctly but it might require a bit of tweaking. You may need to async the function on the actual route itself as well and await the call for getAnswersCount but that should just about do it.