mysql node js quest -- SELECT EXISTS query - mysql

what is wrong with this logic?
var selectString = 'SELECT EXISTS(SELECT 1 FROM users WHERE user="'+username+'")';
var queryUserExists = connection.query(selectString);
var resultsLength = queryUserExists._results.length;
console.log(queryUserExists);
if(resultsLength > 0){
socket.write("fail user already exists"+"\r\n");
} else {
console.log('insert=');
var query = connection.query (
'INSERT INTO users '+
'SET user = ?, password = ?, token = ?',
[username, password, token]
);
socket.write("success"+"\r\n");
}
resultsLength is always returned zero.
What is the proper way to use this query?
returned object:
sql: 'SELECT 1 FROM users WHERE user = \'a new user is my name\' ORDER BY user LIMIT 1',
typeCast: true,
nestTables: false,
_resultSet: null,
_results: [],
_fields: [],
_index: 0,
_loadError: null }

The proper code: thanks to https://stackoverflow.com/users/722783/mahmoud-gamal for the database query that is optimized!
connection.query("SELECT 1 FROM users WHERE user = '"+username+"' ORDER BY user LIMIT 1", function (error, results, fields) {
if (error) {
console.log(error);
socket.write("fail internal error"+"\r\n");
}
if (results.length > 0) {
console.log('fail');
socket.write("fail user already exists"+"\r\n");
} else {
console.log('insert');
var query = connection.query (
'INSERT INTO users '+
'SET user = ?, password = ?, token = ?',
[username, password, token]
);
socket.write("success"+"\r\n");
}
console.log(results);
});

Try this:
SELECT 1
FROM users
WHERE EXISTS (SELECT 1
FROM users
WHERE user = 'username')
ORDER BY user
LIMIT 1;
Or: Why not:
SELECT 1
FROM users
WHERE user = 'username'
ORDER BY user
LIMIT 1;
Note that:
ORDER BY user
LIMIT 1;
Are just for performance.

Related

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"

Node JS for loop and database query

I'm running a for loop on a function, and the database is updated on each loop. It then calls the database again using the for loop to update values on the database. However it seems to appear like i'm getting cached results. Is there any reason for this error?
I can post my code, but it's kind of tedious.
It's a simple for loop on a module function that calls a database request, then updates that database.
module.exports.newElectronicHyperCredit = function(request){
gt = request.body.custom + "-" + Date.now()
db.query(
"SELECT * FROM Tenderizer.Stats ORDER BY ID DESC LIMIT 1",
[
],
function(error, stats){
bsr = stats[0]['BuySellRate'];
dv = stats[0]['DollarValue'];
credits = stats[0]['Credits'];
for(i = 0; i < request.body.quantity; i++){
bsr = dv / credits;
dv = Number(dv) + 10;
credits = Number(credits) + (7 / BSR);
denomination = 7 / bsr;
db.query(
"INSERT INTO Tenderizer.Stats SET ?",
{
BuySellRate: bsr,
DollarValue: dv,
Credits: credits
},
function(error, stats){
}
)
db.query(
"SELECT * FROM Tenderizer.Withdrawals ORDER BY case when Withdrawals.Owner = 'Rah1337' then 1 else 2 end, Withdrawals.ID DESC",
[
],
function(error, withdrawals){
withdrawn = 0;
for(x in withdrawals){
if(denomination != 0){
if(withdrawals[x]['Denomination'] > denomination){
withdrawn = withdrawn + denomination;
db.query(
"UPDATE Tenderizer.Withdrawals SET Denomination = Denomination - ? WHERE ID = ?",
[
denomination,
withdrawals[x]['ID']
],
function(error, points){
}
);
db.query(
"INSERT INTO Tenderizer.Points SET ?",
{
GenerationTag: withdrawals[x]['GenerationTag'],
Owner: request.body.custom,
Denomination: denomination,
BoughtPoint: bsr,
Since: Date.now()
},
function(error, points){
}
);
db.query(
"INSERT INTO Tenderizer.Payouts SET ?",
{
GenerationTag: withdrawals[x]['GenerationTag'],
Owner: withdrawals[x]['Owner'],
DollarValue: bsr * withdrawals[x]['Denomination'],
Denomination: denomination,
Processed: 0,
Since: Date.now()
},
function(error, payouts){
}
);
denomination = 0;
}else{
withdrawn = withdrawn + denomination;
db.query(
"DELETE FROM Tenderizer.Withdrawals WHERE ID = ?",
[
withdrawals[x]['ID']
],
function(error, withdrawals){
}
);
db.query(
"INSERT INTO Tenderizer.Points SET ?",
{
GenerationTag: withdrawals[x]['GenerationTag'],
Owner: request.body.custom,
Denomination: withdrawals[x]['Denomination'],
BoughtPoint: bsr,
Since: Date.now()
},
function(error, points){
}
);
db.query(
"INSERT INTO Tenderizer.Payouts SET ?",
{
GenerationTag: withdrawals[x]['GenerationTag'],
Owner: withdrawals[x]['Owner'],
DollarValue: bsr * withdrawals[x]['Denomination'],
Denomination: withdrawals[x]['Denomination'],
Processed: 0,
Since: Date.now()
},
function(error, payouts){
}
);
denomination = denomination - withdrawals[x]['Denomination'];
}
}
}
if(denomination > 0){
db.query(
"INSERT INTO Tenderizer.Pool SET ?",
{
GenerationTag: gt,
Username: request.body.custom,
DollarValue: 10 - (withdrawn * bsr),
Withdrawn: 0,
Since: Date.now()
},
function(error, pool){
}
);
db.query(
"INSERT INTO Tenderizer.Points SET ?",
{
GenerationTag: gt,
Owner: request.body.custom,
Denomination: denomination,
BoughtPoint: bsr,
Since: Date.now()
},
function(error, points){
}
);
}
db.query(
"UPDATE Tenderizer.EHC_Count SET Credits = Credits + ? WHERE Username = ?",
[
7 / bsr
],
function(error, ehc_count){
}
);
}
);
}
}
);
};
It's not inserting the records one by one, it's inserting it all at once or it's using cached results. Because the rows that i'm recieving in my database are
duplicate rows rather than incrementing rows. In the points table in the denomination column and the bought point.
You're using lots of callbacks, but you're not actually doing anything to wait until those callbacks are called. This is difficult to resolve using callbacks, but could be done much more easily if you use a library that supports Promises.
For example, this is what the code would look like if you properly await each query using #databases/mysql
const createConnectionPool = require('#databases/mysql');
const {sql} = require('#databases/mysql');
const db = createConnectionPool();
module.exports.newElectronicHyperCredit = async function(request){
let gt = request.body.custom + "-" + Date.now()
const stats = await db.query(
sql`SELECT * FROM Tenderizer.Stats ORDER BY ID DESC LIMIT 1`,
);
let bsr = stats[0]['BuySellRate'];
let dv = stats[0]['DollarValue'];
let credits = stats[0]['Credits'];
for(let i = 0; i < request.body.quantity; i++){
bsr = dv / credits;
dv = Number(dv) + 10;
credits = Number(credits) + (7 / BSR);
denomination = 7 / bsr;
await db.query(sql`
INSERT INTO Tenderizer.Stats (BuySellRate, DollarValue, Credits)
VALUES (${bsr}, ${dv}, ${credits}
`)
const withdrawals = await db.query(sql`
SELECT * FROM Tenderizer.Withdrawals
ORDER BY case when Withdrawals.Owner = 'Rah1337' then 1 else 2 end, Withdrawals.ID DESC
`)
withdrawn = 0;
for(x in withdrawals){
if(denomination != 0){
if(withdrawals[x]['Denomination'] > denomination){
withdrawn = withdrawn + denomination;
await db.query(sql`
UPDATE Tenderizer.Withdrawals
SET Denomination = Denomination - ${denomination}
WHERE ID = ${withdrawals[x]['ID']}
`);
await db.query(sql`
INSERT INTO Tenderizer.Points (GenerationTag, Owner, Denomination, BoughtPoint, Since)
VALUES (
${withdrawals[x]['GenerationTag']},
${request.body.custom},
${denomination},
${bsr},
${Date.now()}
)
`);
await db.query(sql`
INSERT INTO Tenderizer.Payouts (GenerationTag, Owner, DollarValue, Denomination, Processed, Since)
VALUES (
${withdrawals[x]['GenerationTag']},
${withdrawals[x]['Owner']},
${bsr * withdrawals[x]['Denomination']},
${denomination},
${0},
${Date.now()}
)
`);
denomination = 0;
}else{
withdrawn = withdrawn + denomination;
await db.query(
sql`DELETE FROM Tenderizer.Withdrawals WHERE ID = ${withdrawals[x]['ID']}`
);
await db.query(sql`
INSERT INTO Tenderizer.Points (GenerationTag, Owner, Denomination, BoughtPoint, Since)
VALUES (
${withdrawals[x]['GenerationTag']},
${request.body.custom},
${withdrawals[x]['Denomination']},
${bsr},
${Date.now()}
)
`);
await db.query(sql`
INSERT INTO Tenderizer.Payouts (GenerationTag, Owner, DollarValue, Denomination, Processed, Since)
VALUES (
${withdrawals[x]['GenerationTag']},
${withdrawals[x]['Owner']},
${bsr * withdrawals[x]['Denomination']},
${withdrawals[x]['Denomination']},
${0},
${Date.now()}
)
`);
denomination = denomination - withdrawals[x]['Denomination'];
}
}
}
if(denomination > 0){
await db.query(sql`
INSERT INTO Tenderizer.Pool (GenerationTag, Username, DollarValue, Withdrawn, Since)
VALUES (
${gt},
${request.body.custom},
${10 - (withdrawn * bsr)},
${0},
${Date.now()}
)
`);
await db.query(sql`
INSERT INTO Tenderizer.Points (GenerationTag, Owner, Denomination, BoughtPoint, Since)
VALUES (
${gt},
${request.body.custom},
${denomination},
${bsr},
${Date.now()}
)
`);
}
await db.query(sql`UPDATE Tenderizer.EHC_Count SET Credits = Credits + ${7 / bsr} WHERE Username = ${request.body.custom}`)
}
};
P.S. it also looks like you're forgetting to actually declare your variables (using let or const before you assign values to them.
P.P.S doing all these queries in a loop may be quite slow, because each one will be executed sequentially. This will be necessary if each query depends on the result of the previous one, but if that's not the case, you could replace one/all of the loops with await Promise.all(list.map(async (value, index) => {...})), which will run the function for each value in the list, but will run it in parallel.

Mysql Error: trying to find columns in database

Im trying to insert user data into my mysql database but Im getting this error " sql: 'SELECT * FROM users WHERE undefined = ?' "
Here is my code :
find: function(user = null, callback) {
//if the user variable is defined
if(user) {
var field = Number.isInteger(user) ? 'id' : 'email';
}
// prepare the sql query
let sql = `SELECT * FROM users WHERE ${field} = ?`;
pool.query(sql, user, function(err, result){
if(err) throw err;
if(result.length){
callback(result[0]);
} else {
callback(null);
}
});
},

making a friend system in node js and mysql

I am building an app where my users can have friends and I store them in a table like this
uid | ownerUid | friendUid
and then I have a users database like this
uid | username | password
and I am trying to make a system to where the user enters the uid of a user into a text box and it adds him as a friend if he is a user and if he is not already his friend using this code
connection.query("SELECT * FROM users WHERE uid = ?", [friendToAddUid], function(err, rows) {
if(rows){
rows.forEach(function(row) {
//is an actual person
connection.query("SELECT * FROM friends WHERE ownerUid = ?", [uid], function(err, rows) {
if(rows){
console.log("user exist")
rows.forEach(function(row){
if (row.friendUid = friendToAddUid){
}else{
var timestamp = new Date().toLocaleDateString("en-US") + ", " + new Date().toLocaleTimeString("en-US");
var row = [ uniqid(), uid, friendToAddUid, timestamp];
connection.query('INSERT INTO friends SET uid=?, ownerUid=?, friendUid=?, since=?', row, function(err) {
console.log(err)
});
}
})
if(rows.length <= 0){
var timestamp = new Date().toLocaleDateString("en-US") + ", " + new Date().toLocaleTimeString("en-US");
var row = [ uniqid(), uid, friendToAddUid, timestamp];
connection.query('INSERT INTO friends SET uid=?, ownerUid=?, friendUid=?, since=?', row, function(err) {
console.log(err)
});
}
}else{
var timestamp = new Date().toLocaleDateString("en-US") + ", " + new Date().toLocaleTimeString("en-US");
var row = [ uniqid(), uid, friendToAddUid, timestamp];
connection.query('INSERT INTO friends SET uid=?, ownerUid=?, friendUid=?, since=?', row, function(err) {
console.log(err)
});
}
})
})
}
})
it adds the user fine and won't add him if he is already your friend but I cant add any more friends after I add one friend and I don't know why
wanted to know if there is an issue with my MySQL query

How to update multiple columns in mysql using nodejs

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}"`;