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
}
}
Related
Below code is for getting sum of quantity from MySql database.
'deger' returns with {"SUM(quantity)":75}
I want to take '75' from that object.
I have tried;
deger.SUM(quantity)
Since SUM is reserved word, it does not work.
connection.query("SELECT SUM(quantity) FROM report WHERE fabrika = ? ", fabrika, function(err, rows) {
if (err) console.log(err);
else {
for (var i = 0; i < rows.length; i++) {
var row = rows[i];
var deger = JSON.stringify(row)
console.log("**********************************");
console.log("Possible Quantity: " + deger); //Possible Quantity: {"SUM(Quantity)":75}
console.log("**********************************");
}
}
});
Thanks to #gview.
Adding 'as quantity' after SELECT, solved the problem.
connection.query("SELECT SUM(quantity) as quantity FROM report WHERE fabrika = ? ", fabrika, function(err, rows) {
if (err) console.log(err);
else {
for (var i = 0; i < rows.length; i++) {
var row = rows[i];
var deger = JSON.stringify(row)
console.log("**********************************");
console.log("Possible Quantity: " + deger); //Possible Quantity: {"SUM(Quantity)":75}
console.log("**********************************");
}
}
});
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]
I am making a game that when you click on the Monster your score gets +1. But when your score goes over 1000 I would like it like this 1,000 rather than 1000. I am not sure how to do this as I have not learnt much action script. I have embed number and punctuation into the font. Here is my code so far:
var score:Number = 0;
Multitouch.inputMode = MultitouchInputMode.TOUCH_POINT;
Monster.addEventListener(TouchEvent.TOUCH_TAP, fl_TapHandler);
function fl_TapHandler(event:TouchEvent):void
{
score = score + 1;
Taps_txt.text = (score).toString();
}
Help will greatly appreciated.
You can do like that:
function affScore(n:Number, d:int):String {
return n.toFixed(d).replace(/(\d)(?=(\d{3})+\b)/g,'$1,');
}
trace(affScore(12345678, 0)); // 12,345,678
This may not be the most elegant approach, but I wrote a function that will return the string formatted with commas;
public function formatNum(str:String):String {
var strArray:Array = str.split("");
if (strArray.length >= 4) {
var count:uint = 0;
for (var i:uint = strArray.length; i > 0; i--) {
if (count == 3) {
strArray.splice(i, 0, ",");
count = 0;
}
count++;
}
return strArray.join("");
}
else {
return str;
}
}
I tested it on some pretty large numbers, and it seems to work just fine. There's no upper limit on the size of the number, so;
trace (formatNum("10000000000000000000"));
Will output:
10,000,000,000,000,000,000
So in your example, you could use it thusly;
Taps_txt.text = formatNum(String(score));
(This is casting the type implicitly rather than explicitly using toString();, but either method is fine. Casting just looks a little neater in function calls)
Use the NumberFormatter class:
import flash.globalization.NumberFormatter;
var nf:NumberFormatter = new NumberFormatter("en_US");
var numberString:String = nf.formatNumber(1234567.89);
trace("Formatted Number:" + numberString);
// Formatted Number:1,234,567.89
To show the score with comma, you can do like this : ( comments are inside the code )
var score:Number = 0;
var score_str:String;
var score_str_len:int;
Multitouch.inputMode = MultitouchInputMode.TOUCH_POINT;
Monster.addEventListener(TouchEvent.TOUCH_TAP, fl_TapHandler);
function fl_TapHandler(event:TouchEvent):void
{
score = score + 1;
score_str = score.toString();
score_str_len = score_str.length;
// here you can use score > 999 instead of score_str_len > 3
Taps_txt.text =
score_str_len > 3
// example : 1780
// score_str_len = 4
// score_str.substr(0, 4 - 3) = 1 : get thousands
// score_str.substr(4 - 3) = 780 : get the rest of our number : hundreds, tens and units
// => 1 + ',' + 780 = 1,780 : concatenate thousands + comma + (hundreds, tens and units)
? score_str.substr(0, score_str_len-3) + ',' + score_str.substr(score_str_len-3)
: score_str
;
// gives :
// score == 300 => 300
// score == 1285 => 1,285
// score == 87903 => 87,903
}
EDIT :
To support numbers greater than 999.999, you can do like this :
function fl_TapHandler(event:MouseEvent):void
{
score = score + 1;
score_str = score.toString();
Taps_txt.text = add_commas(score_str);
}
function add_commas(nb_str:String):String {
var tmp_str:String = '';
nb_str = nb_str.split('').reverse().join('');
for(var i = 0; i < nb_str.length; i++){
if(i > 0 && i % 3 == 0) tmp_str += ',';
tmp_str += nb_str.charAt(i);
}
return tmp_str.split('').reverse().join('');
/*
gives :
1234 => 1,234
12345 => 12,345
123456 => 123,456
1234567 => 1,234,567
12345678 => 12,345,678
123456789 => 123,456,789
1234567890 => 1,234,567,890
*/
}
Hope that can help you.
I have a script where i need to check the username and password and display a msg using sqlite transaction . the status msg displays the appropriate msg at the right entries but the alert msg for the wrong entries would not show up . Can this problem be fixed .The script is as follows:
var db = openDatabase('mydb', '1.0', 'Test DB', 2 * 1024 * 1024);
db.transaction(function (tx) {
tx.executeSql("CREATE TABLE IF NOT EXISTS Contact1(id unique, username TEXT NOT NULL, pass TEXT NOT NULL)");
tx.executeSql("INSERT INTO Contact1(id, username, pass) VALUES (1, 'pp1', '321')");
// tx.executeSql('INSERT INTO LOGS (id, log) VALUES (2, "logmsg")');
});
$(document).ready(function () // Call function when page is ready for load..
{
db.transaction(function (tx) {
tx.executeSql("INSERT INTO Contact1(id, username, pass) VALUES (3, 'pp1', '321')");
});
$("#sub").click(function(){
var uname = $("#username").val();
var password = $("#password").val();
db.transaction(function (tx) {
tx.executeSql('SELECT * FROM Contact1 WHERE username=?', [uname], function (tx, results) {
var len = results.rows.length, i;
// msg = "<p>Found rows: " + len + "</p>";
//document.querySelector('#status').innerHTML += msg;
for (i = 0; i < len; i++){
// msg = "<p><b>" + results.rows.item(i).pass + "</b></p>";
//document.querySelector('#status').innerHTML += msg;
if(results.rows.item(i).username == uname){
// alert("hello");
tx.executeSql('SELECT * FROM Contact1 WHERE pass=?', [password], function (tx, results) {
var len = results.rows.length, i;
msg = "<p>Found rows: " + len + "</p>";
document.querySelector('#status').innerHTML += msg;
for (i = 0; i < len; i++){
msg = "<p><b>" + results.rows.item(i).username + "</b>==><b>" + results.rows.item(i).pass + "</b></p>";
document.querySelector('#status').innerHTML += msg;
}
}, null);
}
else
{//wrong username/password case
msg="<p><b>Please enter the right Username and password"+"</b></p>";
document.querySelector('#status').innerHTML += msg;
}
}
}, null);
});});});
Thanks in advance :D
Suganthi pointed out problem, but nevertheless i decided to rewrite your code to fix a problem and to make code better:
var db;
document.addEventListener("deviceready", onDeviceReady, false);
function onDeviceReady() {
db = openDatabase('mydb', '1.0', 'Test DB', 2 * 1024 * 1024);
db.transaction(function (tx) {
tx.executeSql("CREATE TABLE IF NOT EXISTS Contact1(id unique, username TEXT NOT NULL, pass TEXT NOT NULL)");
tx.executeSql("INSERT INTO Contact1(id, username, pass) VALUES (1, 'pp1', '321')");
tx.executeSql("INSERT INTO Contact1(id, username, pass) VALUES (3, 'pp1', '321')");
});
}
$("#sub").click(function() {
var uname = $("#username").val();
var password = $("#password").val();
db.transaction(function (tx) {
tx.executeSql('SELECT * FROM Contact1 WHERE username = ? AND pass = ?', [uname, password], function (tx, results) {
var len = results.rows.length;
if (len > 0) {
$('#status').append("<p>Found rows: " + len + "</p>");
for (i = 0; i < len; i++) {
msg = "<p><b>" + results.rows.item(i).username + "</b>==><b>" + results.rows.item(i).pass + "</b></p>";
$('#status').append(msg);
}
} else {
msg = "<p><b>Please enter correct username and password</b></p>";
$('#status').append(msg);
}
}, null);
});
});
according to your code
if username is wrong it returns len=0 so it wont enter into else condition.
try this
$("#sub").click(function(){
var uname = $("#username").val();
var password = $("#password").val();
db.transaction(function (tx) {
tx.executeSql('SELECT * FROM Contact1 ', function (tx, results) {
var len = results.rows.length, i;
for (i = 0; i < len; i++){
if(results.rows.item(i).username == uname &&results.rows.item(i).pass == password){
// alert("hello");
msg = "<p><b>" + results.rows.item(i).username + "</b>==><b>" + results.rows.item(i).pass + "</b></p>";
document.querySelector('#status').innerHTML += msg;
}
else
{
msg="<p><b>Please enter the right Username and password"+"</b></p>";
document.querySelector('#status').innerHTML += msg;
}
}
}, null);
I need to fire a dynamic group by query using an array.
a=['Branch','Company','Name'];
now , I need the query like
"select Branch,Company,Name,count(Name) as count from myTable group by Branch,Company,Name;"
Kindly suggest!!
Using your initial question data:
a=['Branch','Company','Name'];
function addCount(a) {
db.transaction(function (tx) {
str=a.join(", ");
tx.executeSql("select "+str+",count(*) as count from documentProperty GROUP BY "+str+";", [], function (tx, result) {
if (result != null && result.rows != null) {
for (var i = 0; i < result.rows.length; i++) {
var row = result.rows.item(i);
console.log(row);
}
}
});
});
}
Try this:
String quryString = "select Branch,Company,Name,count(Name) as count from myTable group by " ;
for (int i = 0; i < a.length; i++)
quryString =quryString +a[i];
now use quryString and fire your query.
Thanks Guys,
I tried and finally got my result from the following code.
jsonString=[{"field":"Branch"},{"field":"Company"},{"field":"Name"}]
function addCount(jsonString){
var a=[];
var str="";
$.each(jsonString,function (i,result){
a.push(result.field);
if(i == jsonString.length-1){
str += result.field;
} else{
str += result.field+",";
}
});
db.transaction(function (tx) {
var q=(a.length-1);
var query="select "+str+",count("+a[q]+") as count from documentProperty GROUP BY "+str+";"; console.log(query);
tx.executeSql(query, [], function (tx, result) {
if (result != null && result.rows != null) {
for (var i = 0; i < result.rows.length; i++) {
var row = result.rows.item(i);
console.log(row);
}
}
});
});
}