INSERT INTO fails with node-mysql - variable is always NULL - mysql

I am using MySql with node.js
I have this query and it not works, temp1 in MySQL is alwayls NULL:
var queryTemp1 = { tid: '1', temp: temp1, timestamp: myDate };
con.query('INSERT INTO temps SET ?', queryTemp1, function(err,res){
if(err) throw err;
console.log('Last insert ID:', res.insertId);
});
temp1 is float I think- - i can print it and everything is OK:
var temp1 = parseFloat(stdout);
var temp1 = temp1/1000
var temp1 = (temp1.toFixed(2));
My table has columns:
+-----------+-------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+-----------+-------------+------+-----+---------+-------+
| tid | smallint(6) | YES | | NULL | |
| timestamp | datetime | YES | | NULL | |
| temp | float(4,2) | YES | | NULL | |
+-----------+-------------+------+-----+---------+-------+
What am I doing wrong?

That INSERT statement doesn't look right...
Try this:
// BIND PARAMS
var queryTemp1 = { tid: '1'
, temp: temp1
, timestamp: myDate
};
// VARIABLE FOR SQL
var sql = "INSERT INTO temps(tid, temp, timestamp)\
VALUES (:tid, :temp, :timestamp)";
// DATABASE
con.query( sql
, queryTemp1
, function(err, res) {
if(err) throw err;
console.log('Last insert ID:', res.insertId);
});

tid is currently a string and its looking for a tinyint, try taking the single quotes away and see if that fires.
Also make sure your datetime is a datetime not actually a timestamp, ie something like 2014-01-01 00:00:00 and not 1231232131
Edit: your code here could be scrubbing the value,
var temp1 = parseFloat(stdout);
var temp1 = temp1/1000
var temp1 = (temp1.toFixed(2));
if you need to update temp1, take the var out.
var temp1 = parseFloat(stdout);
temp1 = temp1/1000
temp1 = (temp1.toFixed(2));

Here is entire code:
var mysql = require("mysql");
var child_process = require('child_process');
var temp1;
// First you need to create a connection to the db
var con = mysql.createConnection({
host: "localhost",
user: "user",
password: "password",
database: "database"
});
con.connect(function(err){
if(err){
console.log('Error connecting to Db');
return;
}
console.log('Connection established');
});
console.log(temp1);
child_process.exec("sudo -u www-data grep -a 't=' /var/www/temp/w1_slave | cut -f2 -d=", function (err, stdout, stderr){
if (err) {
console.log("child processes failed with error code: " +
err.code);
}
console.log(stdout);
temp1 = parseFloat(stdout);
temp1 = temp1/1000
temp1 = (temp1.toFixed(2));
});
var moment = require('moment');
var now = moment();
myDate = moment(now.format('YYYY/MM/DD HH:mm:ss')).format("YYYY-MM-DD HH:mm:ss");
var queryTemp1 = [1, temp1];
// VARIABLE FOR SQL
var sql = "INSERT INTO temps(tid, temp) VALUES (?)";
// DATABASE
con.query(sql
, queryTemp1
, function(err, res) {
if(err){console.log(queryTemp1); throw err;}
console.log('Last insert ID:', res.insertId);
});
console.log(queryTemp1);

A working example of my use case that inserts a row and returns the insertId:
Function definition:
const sleep = (waitTimeInMs) => new Promise(resolve => setTimeout(resolve, waitTimeInMs));
const insertLog = async (db, requestUrl, requestType, isRequestSuccessful) => {
let insertId = null;
const stmt = 'insert into logs(request_url, request_type, request_status) values (?, ?, ?)';
const insertData = [requestUrl, requestType, isRequestSuccessful ? 'successful' : 'failed'];
db.query(stmt, insertData, (err, result, fields) => {
if (err) {
throw err;
}
insertId = result.insertId;
});
while(insertId === null) {
await sleep(100);
}
return insertId;
};
Usage:
const logId = await insertLog(mysqlConnection, browseUrl, 'browse', false);
I'm using mysql package v2.18.1 and node v15.4.0.
Should be easy to adjust to your use case, for example
const insertId = await insert(mysqlConnection, data);

Related

Log Missing Column in Destination Spreadsheet

I have the code below which allows me to update the existing spreadsheet (much like an matrix lookup). And what I am doing right now is to include a error log which will be updated in another sheet, this includes Missing data in Column A in Destination Spreadsheet and Missing Column in Destination Spreadsheet. I have worked with Missing data in Column A, my problem was the Missing Column, cause instead of the column name (found in the row 1) the result shows the column index:
code:
function updateShadowSKU() {
var source = SpreadsheetApp.getActive().getSheetByName('Sheet1');
var dest = SpreadsheetApp.openById('179PCrIWe1mvbbzOi9ySEHxzBlFaXpCB2i0wHlYVE2vg').getSheetByName('Sheet1');
var destRange = dest.getDataRange();
var destValues = destRange.getValues();
var destHeaders = destValues[0];
var destIds = destValues.map(e => e[0]);
var values = source.getDataRange().getValues().map(e => e.filter((f, i) => !i || i > 10));
var colMap = values[0].map(e => destHeaders.indexOf(e));
Logger.log(colMap);
values = values.map((e, i, arr) => e.map((f, j) => [e[0], colMap[j], f, values[0][j], i, j])).flat().filter(e => e[0] && e[1] && e[2] && e[3] && e[4] && e[5]);
Logger.log(values);
// Initialize an array to store log entries
var logEntries = [];
// Check for missing SKUs
values.forEach(function(e) {
if (!destIds.includes(e[0])) {
logEntries.push(["Missing SKU", e[0], e[3]]);
}
});
// Check for missing column headers
colMap.forEach(function(e, i) {
if (e == -1) {
var index = destHeaders.indexOf(values[0][i]);
colMap[i] = index;
if (index == -1) {
logEntries.push(["Missing column header", values[0][e], ""]);
}
}
});
if (!values.length) {
logEntries.push(["No changes to make", "", ""]);
} else {
values = values.map(e => [destIds.indexOf(e[0]), e[1], e[2]]);
Logger.log(values.length + ' changes to make');
Logger.log(values);
values.forEach(function(e) {
try {
destValues[e[0]][e[1]] = e[2];
} catch (err) {}
});
destRange.setValues(destValues);
}
// Write log entries to the 'Shadow Log' sheet in the destination spreadsheet
if (logEntries.length > 0) {
var logSheet = SpreadsheetApp.openById('179PCrIWe1mvbbzOi9ySEHxzBlFaXpCB2i0wHlYVE2vg').getSheetByName("Shadow Log");
if (logSheet == null) {
logSheet = SpreadsheetApp.openById('179PCrIWe1mvbbzOi9ySEHxzBlFaXpCB2i0wHlYVE2vg').insertSheet("Shadow Log");
}
logSheet.clear();
logSheet.getRange(1, 1, logEntries.length, 3).setValues(logEntries);
}
}
the code block for getting the missing data in Column A destination spreadsheet works fine, but what I am having a hard time is getting the column name. The code block below shows only the column index instead of the comlumn title/header:
// Check for missing column headers
colMap.forEach(function(e, i) {
if (e == -1) {
var index = destHeaders.indexOf(values[0][i]);
colMap[i] = index;
if (index == -1) {
logEntries.push(["Missing column header", values[0][e], ""]);
}
}
});
sample sheets:
source: https://docs.google.com/spreadsheets/d/1zGqiYocUmSBRDPKRqI3iI3nIf7w3b9C7ykT-QffBROA/edit#gid=0
destination: https://docs.google.com/spreadsheets/d/1PjOvhscblzPxaBnJi1Q5oB6iCAt9_emljUR6vlAfIA0/edit#gid=0
example:
source data:
| SKU | walmart1 | amazon 2 | ebay1 |
|============|==============|==============|===========|
| SKUitem1 | SKUwm1 | | SKUebay1 |
| SKUitem2 | | | SKUitem5 |
| SKUitem3 | SKUwmi1 | | |
destination:
| items | **walmart2** | **amazon 1** | ebay1 |
|============|==============|==============|===========|
| SKUitem1 | SKUwm1 | | SKUebay1 |
|**SKUitem5**| | | |
| SKUitem3 | | | |
desired result:
in this scenario the 'Shadow Log' sheet should result into
| Missing SKU | SKUitem2 |
| Missing Column | walmart1 |
missing SKU - cause there were an update from the source but unable to find it in the destination
missing column - cause there were an update on that column but unable to find that column
you will also see that there is a mismatch column amazon 2 --> amazon 1, but you will see nothing in the desired results, it is because there's no new data to be updated.
I hope this clears things out, please don't hesitate to ask me
Check and Fix the Index when Accessing Desired Data
I noticed that when you tried to access the data from values, you used [e] as the index which will lead to an undefined value since [e] will always be -1 in your case and there is no -1 index in an arrays.
Also, when using the forEach method, the first variable (e in your case) will be the value to be processed while the second variable will be the index value (i in your case). Hence, you should use [i] when accessing data using loops.
With all that, I added a sourceCol variable to store all wanted column headers from the source.
You may change the range if you should add more columns. I changed values[0][e] to sourceCol[0][i] to access the wanted column header.
The new code should look like this: (I added comments for further guidance)
function updateShadowSKU() {
var source = SpreadsheetApp.getActive().getSheetByName('Sheet1');
var dest = SpreadsheetApp.openById('Destination Sheet ID').getSheetByName('Sheet1');
var destRange = dest.getDataRange();
var destValues = destRange.getValues();
var destHeaders = destValues[0];
var destIds = destValues.map(e => e[0]);
var values = source.getDataRange().getValues().map(e => e.filter((f, i) => !i || i > 10));
//-----------------------------------------------------------------------------------------------
//added sourceCol variable to specifically get the array of all Column Headers from the Source
var sourceCol = source.getDataRange().getValues().map(e => e.filter((f, i) => i >= 3 && i <= 17));
var colMap = sourceCol[0].map(e => destHeaders.indexOf(e));
//-----------------------------------------------------------------------------------------------
values = values.map((e, i, arr) => e.map((f, j) => [e[0], colMap[j], f, values[0][j], i, j])).flat().filter(e => e[0] && e[1] && e[2] && e[3] && e[4] && e[5]);
// Initialize an array to store log entries
var logEntries = [];
// Check for missing SKUs
values.forEach(function (e) {
if (!destIds.includes(e[0])) {
logEntries.push(["Missing SKU", e[0], e[3]]);
}
});
// Check for missing column headers
colMap.forEach(function (e, i) {
if (e == -1) {
//--------------------------------------------------------------
//change values[0][e] to sourceCol[0][i]
logEntries.push(["Missing column header", sourceCol[0][i], ""]);
//--------------------------------------------------------------
}
});
if (!values.length) {
logEntries.push(["No changes to make", "", ""]);
} else {
values = values.map(e => [destIds.indexOf(e[0]), e[1], e[2]]);
Logger.log(values.length + ' changes to make');
Logger.log(values);
values.forEach(function (e) {
try {
destValues[e[0]][e[1]] = e[2];
} catch (err) { }
});
destRange.setValues(destValues);
}
// Write log entries to the 'Shadow Log' sheet in the destination spreadsheet
// Added an else statement to clear the 'Shadow Log` when the log is empty.
var logSheet = SpreadsheetApp.openById('Destination Sheet ID').getSheetByName("Shadow Log");
if (logEntries.length > 0) {
if (logSheet == null) {
logSheet = SpreadsheetApp.openById('Destination Sheet ID').insertSheet("Shadow Log");
}
logSheet.clear();
logSheet.getRange(1, 1, logEntries.length, 3).setValues(logEntries);
}
else {
logSheet.clear();
}
}
Output
In testing the code, I deleted 5 column headers (as seen below):
When I ran the code with the modification, I got the following output:
References
forEach
Accessing Arrays

How to update all columns at once in Mysql

There is a database with 200 columns, how to update data from 21 to 200, not in this way -
Set Column21 = NEW.Column21,
Column22 = NEW.Column22,
Column23 = NEW.Column23,
Column24 = NEW.Column24,
Column25 = NEW.Column25...
//You can loop through 22 to 200 and make the string or access property
let sql = "Set",i=22;
[...Array(179)].forEach((_, l) => {
let column = 'Column'+i;
let val = "some val"; //access value
sql += ` ${column} = ${val} `;
i++;
});
console.log(sql);

Why is my code still running as asynchronous even though I have the Promise and await values

I need to run a if else statement then run a map inside of this if else, and after that run the queries, but it's just running as asynchronous.
This is the code below that is broken. I have no idea how to fix it.
function newRank() {
return new Promise((resolve, reject) => {
// If the select from target table is empty, then run this if below
if (rank_atual.length == 0) {
console.log('RANK ATUAL IF')
// Map new rank to add into target table
rank_gender.map(async (rnk) => {
// Query that will be feed by rank array and put that on the target table
let sql_insert = `INSERT INTO rnk_rank_diario (nr_rank_sem_genero, qt_tocadas, fk_id_fonogramas, fk_id_artista, fk_id_rnk_local_record, fk_id_rnk_tipo_emissora, fk_id_rnk_relevancia_local, fk_id_rnk_tipo_emissora_nr_relevancia, dh_sem_genero_criado, dh_sem_genero_alterado, nr_rank_com_genero, dh_com_genero_criado, dh_com_genero_alterado, fl_ativo, fk_id_fonogramas_genero, fl_record_sem_genero, fl_record_com_genero) VALUES (${rnk.rank}, ${rnk.total}, ${rnk.fonograma}, ${rnk.artista}, 1, ${rnk.categoria}, 5, 5, current_timestamp(), NULL, ${rnk.rank_genero}, current_timestamp(), NULL, 1, ${rnk.genero}, 1, 1)`;
// console.log(sql_insert)
// Run the query above, and check if everything goes fine.
conInsert.query(sql_insert, function (err, result) {
if (err) return reject(err);
})
})
}
else {
console.log('RANK ATUAL ELSE')
// Map new rank to add into target table
rank_gender.map((rnk) => {
// Find the index on the actual rank using the new rank fonogram
let ra = rank_atual.findIndex(obj => obj.fk_id_fonogramas == rnk.fonograma)
// if the position have been find, run the condition below
if (ra > 0) {
console.log(rnk.fonograma)
console.log(rank_atual[ra].fk_id_fonogramas)
console.log(rank_atual[ra].nr_rank_sem_genero)
// if the actual rank is less then NEW rank, then run the condition below
if (rnk.rank < rank_atual[ra].nr_rank_sem_genero && rnk.rank_genero < rank_atual[ra].nr_rank_com_genero ) {
// console.log(rank_atual[ra + 1].nr_rank_sem_genero)
// Query to update the old record changing the date and the flag to set inactive
let sql_update = `UPDATE rnk_rank_diario SET dh_sem_genero_alterado = current_timestamp(), dh_com_genero_alterado = current_timestamp(), fl_ativo = 0 WHERE fk_id_fonogramas = ${rank_atual[ra].nr_rank_sem_genero} AND fk_id_rnk_local_record = 1 AND fk_id_rnk_tipo_emissora = 5 AND fl_ativo = 1;`;
// Query to insert the new record with the new values.
let sql_insert = `INSERT INTO rnk_rank_diario (nr_rank_sem_genero, qt_tocadas, fk_id_fonogramas, fk_id_artista, fk_id_rnk_local_record, fk_id_rnk_tipo_emissora, fk_id_rnk_relevancia_local, fk_id_rnk_tipo_emissora_nr_relevancia, dh_sem_genero_criado, dh_sem_genero_alterado, nr_rank_com_genero, dh_com_genero_criado, dh_com_genero_alterado, fl_ativo, fk_id_fonogramas_genero, fl_record_sem_genero, fl_record_com_genero) VALUES (${rnk.rank}, ${rnk.total}, ${rnk.fonograma}, ${rnk.artista}, 1, ${rnk.categoria}, 5, 5, current_timestamp(), NULL, ${rnk.rank_genero}, '${moment(rank_atual[ra].dh_sem_genero_criado).utc().format('YYYY-MM-DD HH:MM:SS')}', NULL, 1, ${rnk.genero}, 1, 1);`;
// Run the update query, and check if everything goes fine.
conInsert.query(sql_insert, function (err, result) {
if (err) return reject(err)
});
// Run the insert query, and check if everything goes fine.
conInsert.query(sql_update, function (err, result) {
if (err) return reject(err)
});
}
} else {
console.log('OTHER ELSE')
// Query to create new records on the table if that song doesn't exist yet
let sql_insert = `INSERT INTO rnk_rank_diario (nr_rank_sem_genero, qt_tocadas, fk_id_fonogramas, fk_id_artista, fk_id_rnk_local_record, fk_id_rnk_tipo_emissora, fk_id_rnk_relevancia_local, fk_id_rnk_tipo_emissora_nr_relevancia, dh_sem_genero_criado, dh_sem_genero_alterado, nr_rank_com_genero, dh_com_genero_criado, dh_com_genero_alterado, fl_ativo, fk_id_fonogramas_genero, fl_record_sem_genero, fl_record_com_genero) VALUES (${rnk.rank}, ${rnk.total}, ${rnk.fonograma}, ${rnk.artista}, 1, ${rnk.categoria}, 5, 5, current_timestamp(), NULL, ${rnk.rank_genero}, current_timestamp(), NULL, 1, ${rnk.genero}, 1, 1);`;
// console.log(sql_insert)
// Run the query above, and check if everything goes fine.
conInsert.query(sql_insert, function (err, result) {
if (err) return reject(err);
})
}
})
}
called by:
// Rodar as funções uma a uma.
async function mestre() {
// Function to get the new rank from rnkYYYYMM table
let result = await runSelectRank();
// Function to get the actual rank from rnk_rank_diario
result = await runSelectRank_Atual();
// Function to get the rank and insert them on the rank key inside of the objects
result = await getResult();
// Function to get the rank based on music gender
result = await getGenderResult();
// Function to verify and create the new ranks
result = await newRank();
// Function to close those connectios that were opened to insert into tables
result = await conInsert.end();
// Function to close those connectios that were opened to select from tables
result = await conSelect.end();
}
this is an example of what the code is doing instead of waiting finishing and running
30354
30354
776
18758
18758
946
43614
43614
498
28963
28963
839
9814
9814
834
OTHER ELSE
OTHER ELSE
OTHER ELSE
OTHER ELSE
OTHER ELSE
OTHER ELSE
OTHER ELSE
OTHER ELSE
OTHER ELSE
OTHER ELSE
OTHER ELSE
OTHER ELSE
OTHER ELSE
OTHER ELSE
OTHER ELSE
OTHER ELSE
5. newRank rodou ok
When 5. newRank rodou ok shows on the screen, then the queries start to run, after pass by ALL if else statement, am I missing something??

Node Js mysql multiple query issues

I am working on IO project and I am having issue, when I am trying to do multiple mysql queries under one funtionality.
When match win Calculations are happening Mysql selects just does not happen and error is being thrown that winner object is missing.
I have tried to resolve this in multiple ways:
1) When I tried to nest second select query under first select query result functionality - It did throw Mysql error
Error: Cannot enqueue Quit after invoking quit.
2) I tried to remove all conenction.end() and leave just one at the end of calcualtion functionality. -> It resulted in
Cannot enqueue Query after invoking quit.
Does anyone have any tips how to adjust code in manner, where I can have queries nested one after another, I believe that I have missed some minor detail.
if(data.gameStatus == 'calculation'){
//winner data
mysqlConnect();
connection.query('SELECT * FROM users where username = "'+data.winnerData.username+'"', function(err, result){
if(err){
getDateTimeNow();
console.log(err);
console.log(datetime+' Error occured while calculating game score for'+ data.winnerData.username);
console.log('============================================================');
}
else{
winner = result;
}
});
//loser data
connection.query('SELECT * FROM users where username = "'+data.winnerData.username+'"', function(err, result){
if(err){
getDateTimeNow();
console.log(err);
console.log(datetime+' Error occured while calculating game score for'+ data.loserData.username);
console.log('============================================================');
}
else{
loser = result;
}
});
// rank calculations
var gameTime = data.gameTime;
var winnerPointsBefore = winner[0].points;
var winnerRank = winner[0].rank;
var winnerDefuses = data.winnerData.minesDefused;
var winnerFlags = data.winnerData.fieldsFlagged;
var winnerId = winner[0].id;
var winnerUsername = winner[0].username;
var winnerGamesWon = winner[0].games_won;
var winnerGamesLost = winner[0].games_lost;
var winnerCoins = winner[0].coins;
var timeBonus = 0;
var rankPointAfterModifier = 0;
var loserRank = loser[0].rank;
var loserPointsBefore = loser[0].points;
var loserDefuses = data.losetData.minesDefused;
var loserFlags = data.loserData.fieldsFlagged;
var loserId = loser[0].id;
var loserUsername = loser[0].username;
var loserGamesWon = loser[0].games_won;
var loserGamesLost = loser[0].games_lost;
var loserCoins = loser[0].coins;
if(winnerPointsBefore - loserPointsAfter > 700){
//If pro is facing noob which is 1.5 rank bellow he cannot gain more or less than 15 point
rankPointAfterModifier = 15;
}else{
if(winnerDefuses == 10 && winnerFlags >= winnerDefuses){
//Game won by defusing all mines -> time bonus calculations depending on rank
timeBonus = 70 - 10*winnerRank - gameTime;
if(loserFlags > loserDefuses){
loserFalseFlags = loserFlags - loserDefuses;
opponentPointReduction = 5 * (loserDefuses - loserFalseFlags);
if(opponentPointReduction < 0) {
opponentPointReduction = 0;
}
}else{
opponentPointReduction = 5 * loserDefuses;
}
pointsGained = (winnerDefuses * 5) - opponentPointReduction + timeBonus;
}else{
//Game won by opponent exploding(retard lose scenario)
if(loserFlags > loserDefuses){
loserFalseFlags = loserFlags - loserDefuses;
opponentPointReduction = 5 * (loserDefuses - loserFalseFlags);
if(opponentPointReduction < 0) {
opponentPointReduction = 0;
}
}else{
opponentPointReduction = 5 * loserDefuses;
}
pointsGained = 5 * (winnerDefuses * (winnerFlags / winnerDefuses)) - opponentPointReduction;
}
if(winnerRank != loserRank){
rankPointAfterModifier = -0.2 * (winnerRank-loserRank) * pointsGained;
}
else{
rankPointAfterModifier = pointsGained;
}
}
winnerCoinsEarned = Math.floor(rankPointAfterModifier / 2);
loserCoinsEarned = Math.floor(rankPointAfterModifier / 5);
winnerPointsAfter = winnerPointsBefore + rankPointAfterModifier;
loserPointsAfter = loserPointsBefore - rankPointAfterModifier;
// Register game data in sql
var gameLog = {
winner_id: winnerId,
loser_id: loserId,
winner_name: winnerUsername,
loser_name: loserUsername,
winner_defuses: winnerDefuses,
winner_flagged: winnerFlags,
loser_defuses: loserDefuses,
loser_flagged: loserFlags,
game_time: gameTime,
rank_exchanged: rankPointAfterModifier,
winner_coins_gain: winnerCoinsEarned,
loser_coins_gain: loserCoinsEarned
}
connection.query('INSERT INTO gamelog SET ?', gameLog, function(err, result){
if(err){
getDateTimeNow();
console.log(err);
console.log(datetime+' Error occured while Registering game Log 1337');
console.log('============================================================');
}
getDateTimeNow();
console.log(datetime+ "Game result has been registered: "+result.insertId);
console.log('============================================================');
});
//Register data to game history for player
//winner
winnerGamesWon++;
winnerRankNow = 1;
if(winnerPointsAfter >= 1500){
winnerRankNow = 2;
}
if(winnerPointsAfter >= 1800){
winnerRankNow = 3;
}
if(winnerPointsAfter >= 2100){
winnerRankNow = 4;
}
if(winnerPointsAfter >= 2500){
winnerRankNow = 5;
}
totalWinnerCoins = winnerCoins + winnerCoinsEarned;
connection.query('UPDATE users SET games_won = '+winnerGamesWon+', coins = '+totalWinnerCoins+', points ='+winnerPointsAfter+',rank = '+winnerRankNow+' WHERE id = '+winnerId, function(err, result){
if(err){
getDateTimeNow();
console.log(err);
console.log(datetime+' Error occured while Updating winner rank points 1336');
console.log('============================================================');
}
getDateTimeNow();
console.log(datetime+ "Rank point has been updated for: "+ winnerUsername);
console.log('============================================================');
});
//winner
loserGamesLost++;
loserRankNow = 1;
if(loserPointsAfter >= 1500){
loserRankNow = 2;
}
if(loserPointsAfter >= 1800){
loserRankNow = 3;
}
if(loserPointsAfter >= 2100){
loserRankNow = 4;
}
if(loserPointsAfter >= 2500){
loserRankNow = 5;
}
totalLoserCoins = loserCoins + loserCoinsEarned;
connection.query('UPDATE users SET games_lost = '+loserGamesLost+', coins= '+totalLoserCoins+', points ='+loserPointsAfter+',rank = '+loserRankNow+' WHERE id = '+loserId, function(err, result){
if(err){
getDateTimeNow();
console.log(err);
console.log(datetime+' Error occured while Updating winner rank points 1336');
console.log('============================================================');
}
getDateTimeNow();
console.log(datetime+ "Rank point has been updated for: "+ winnerUsername);
console.log('============================================================');
});
returnData = {
loser : {
username: loserUsername,
rankPointsBefore: loserPointsBefore,
rankPointsAfter: loserPointsAfter,
loserCoinsEarned: loserCoinsEarned
},
winner : {
username: winnerUsername,
rankPointsBefore: winnerPointsBefore,
rankPointsAfter: winnerPointsAfter,
winnerCoinsEarned: winnerCoinsEarned
},
totalRankPoints: winnerPointsBefore + loserPointsBefore
}
}

MySQL query WHERE with object as result

I'm searching data.mesaj in mySQL query but connection is running cause query isn't running, what will do now also data.mesaj have, but I don't want this:
data = { mesaj: '\nHello', uid: 'mustafa' }
y=data.mesaj;
var row = [];
connection.query('select * from yapay_zeka where yapay_zeka.soru = y ', function (err, rows) {
if (err) {
console.log(err);
} else {
if (rows.length) {
for (var i = 0, len = rows.length; i < len; i++) {
row[i] = rows[i];
console.log(row);
}
}
}
connection.query("SELECT * from yapay_zeka WHERE yapay_zeka = '"+y+"'",
function(err, data) {});
connection.query("SELECT * from yapay_zeka WHERE yapay_zeka = '"+y+"'",
function(err, data) {});
I found it:
connection.query("select * from yapay_zeka where yapay_zeka.soru = ?',[data.mesaj]