I've got the following code in NodeJS using an Async/Promises wrapper for Mysql ;
row_c = await db.query( 'SELECT tagid FROM tags WHERE tagname = ?', [tag1] );
How do I now check if there is a result for an IF statement?
I tried;
if (row_c.tagid){
///some code
}
But it's not picking up the conditional. How do I check if the query returned a row?
db.query returns an array of rows. You can do the following:
row_c = await db.query( 'SELECT tagid FROM tags WHERE tagname = ?', [tag1] );
if (row_c.length) {
// if data is returned
console.log(row_c);
}
Related
I want to write a query in MySQL for filtering. For example, if there is a column id in table table1 where the filter values for id come in a POST request body, saved in variable A. I want to extract the matching rows if A is not empty and return all rows otherwise. I am not sure about using IN with WHERE.
SELECT * FROM table1 WHERE id IN (A)
One option is that I return all rows from the database and use JavaScript filters, but I don't want to return all rows and expose the entire table to user.
NOTE: A can be a single value, a tuple or an array.
If you use javascript, use A.join(), and sanitize your POST.
var your_post = [1, 2, 3];
var A = your_post.join();
if (A == '') {
var sql = 'SELECT * FROM table1';
con.query(sql, function (err, result) {
if (err) throw err;
console.log(result);
});
} else {
var sql = 'SELECT * FROM table1 WHERE id IN (?)';
con.query(sql, [A], function (err, result) {
if (err) throw err;
console.log(result);
});
}
My query was like:
let query = `SELECT id, name FROM students WHERE school_code = "${schoolCode}" AND name REGEXP "${text}" `;
And with params:
let params = [ schoolCode, text ];
let query = `SELECT id, name FROM students WHERE school_code = "?" AND name REGEXP "?" `
Model.dataSource.connector.query(query, params, (err, res) => {} );
And it wouldn't work
(Solution below)
I thought maybe it was the REGEXP but
The Solution Was:
to remove quotes around the question marks.
e.g., this worked:
let params = [ schoolCode, text ];
let query = `SELECT id, name FROM students WHERE school_code = ? AND name REGEXP ? `
Model.dataSource.connector.query(query, params, (err, res) => {} );
I have this Mysql query that is working fine. However, I need to add 2 more conditions and I'm not sure how to do this.
//index.js
module.exports = {
getHomePage: (req, res) => {
let query ='SELECT Tbl_Email_mensagens.codigo AS Codigo, Tbl_Email_mensagens.mensagem AS Mensagem,Tbl_Email_mensagens.celular AS Celular, cm_custmaster.fullname AS NomeCompleto FROM Tbl_Email_mensagens LEFT JOIN cm_custmaster ON Tbl_Email_mensagens.celular = cm_custmaster.mobile';
// execute query
db.query(query, (err, result) => {
if (err) {
res.redirect('/');
}
res.render('index.ejs', {
title: ""
,players: result
});
});
},
};
I then need to add these 2 conditions:
Where group = '7' and send = '0'
Very thanks!
SELECT Tbl_Email_mensagens.codigo AS Codigo,
Tbl_Email_mensagens.mensagem AS Mensagem,
Tbl_Email_mensagens.celular AS Celular,
cm_custmaster.fullname AS NomeCompleto
FROM Tbl_Email_mensagens
LEFT JOIN cm_custmaster ON Tbl_Email_mensagens.celular = cm_custmaster.mobile
WHERE Tbl_Email_mensagens.`group` = 7
AND Tbl_Email_mensagens.send = 0
Pay attention - the word group is reserved one, so it MUST be wrapped into backticks. But it is more safe to rename it, to some group_number, for example.
Whereas the quotes over the values are excess (you may store them if according field has any string datatype).
I am trying to write mysql subquery sql in knex but the results of query are undesired.
This is my MySQL query:
select *
from istifta
where istifta_id not in (
select istifta_id
from status
where status = 'divided'
)
This is my query converted to Knex:
subquery = await ctx.knex
.select('istifta_id')
.from('status')
.where('status', 'divided')
result = await ctx.knex
.select()
.from('istifta')
.where('istifta_id', 'not in', subquery)
MySQL query is returning two rows all of which doesn't have status = 'divided'
While Knex is returning three rows with a row having status = 'divided'
You can use .whereNotIn together with the function() definition option to nest your subquery. Your subquery is inside of the function() as:
select('istifta_id').from('status').where('status', 'divided')
and the .on functions just make debugging a bit easier.
result = await ctx.knex.from('istifta')
.whereNotIn( 'istifta_id', function() {
this.select('istifta_id').from('status').where('status', 'divided')
})
.on('query', function(data) {
console.log("TEST001 data:", data); })
.on('query-error', function(ex, obj) {
console.error("TEST002 KNEX query-error ex:", ex, "obj:", obj);
})
How to update the multiple columns in MySQL using node.js:
var query = 'UPDATE employee SET profile_name = ? WHERE id = ?';
connection.query(query,[req.name,req.id] function (error, result, rows, fields) {
but I have to update profile_name, phone,email, country, state, address at once.
How can I do that, can anyone suggest.
Simply add all columns in set:
var query = 'UPDATE employee SET profile_name = ?, phone =?, .. WHERE id=?';
connection.query(query,[req.name,req.phone,...,req.id] function (error, result, rows, fields) {
👨🏫 To update your multiple columns in mysql using nodejs, then You can do it like this code below: 👇
const query = 'UPDATE `employee` SET ? WHERE ?';
connection.query(query, [req.body, req.params], function(err, rows) {
if(err) {
console.log(err.message);
// do some stuff here
} else {
console.log(rows);
// do some stuff here
}
});
💡 Make sure your req.body is not empty and the field in your req.body it's same with the field in your employee table.
If your req.body is undefined or null, then you can add this middleware to your express server:
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
I hope it can help you 🙏.
UPDATE statement syntax :
UPDATE <TableName>
SET <Col1> = <Val1>,
<Col2> = <Val2>,
....
WHERE id = ?
If you have multiple columns update, and need to take the values from the Object,
you can do the following-
let data = {
"table": {
"update_table":"dlrecustomer"
},
"result": {
"pro":"blre",
"pro_id":"BFCA",
"MOBILE":"9506443333",
},
"keys": {
"CUSTOMER":"27799144",
"APPLICATION":"5454642463"
},
}
let update_set = Object.keys(data.result).map(value=>{
return ` ${value} = "${data.result[value]}"`;
});
let update_query = `UPDATE ${data.table.update_table} SET ${update_set.join(" ,")} WHERE CUST_ID = "${data.keys.CUSTOMER}" AND APPL_ID = "${data.keys.APPLICATION}"`;