else condition in script with sqlite - html

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);

Related

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
}
}

Parsing MySql Query with Reserved Word

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("**********************************");
}
}
});

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]

Dynamic group by query

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);
}
}
});
});
}

How to export (dump) WebSQL data

I'm working on a Chrome Extension that uses WebSQL to store historical data.
Being WebSQL, the DB is stored on the client.
I'd like to add an option to export/import such data so that the user can share/use this data with other users, or with other PCs.
These are my first steps on a client-only database, so I wonder how to do this.
I was thinking to convert the DB to a huge json string that the user can copy/paste but doesn't look very user-friendly.
Is there any better solution?
I got a single table dump solution working on a HTML5 database client I wrote a few days ago.
Check out http://html5db.desalasworks.com/script.js and scroll down to SqlClient.exportTable, this has an example that needs to be expanded to cover the whole database.
The steps are:
Step 1: Create the schema:
SELECT sql FROM sqlite_master
Step 2: Get a list of tables:
SELECT tbl_name from sqlite_master WHERE type = 'table'
Step 3: Loop through each of them and create an INSERT script with the results
transaction.executeSql("SELECT * FROM " + _tbl_name + ";", [],
function(transaction, results) {
if (results.rows) {
for (var i = 0; i < results.rows.length; i++) {
var row = results.rows.item(i);
var _fields = [];
var _values = [];
for (col in row) {
_fields.push(col);
_values.push('"' + row[col] + '"');
}
_exportSql += ";\nINSERT INTO " + _tbl_name + "(" + _fields.join(",") + ") VALUES (" + _values.join(",") + ")";
}
}
}
);
Hope this is useful.
UPDATE JAN 2016 - WHOLE DB EXPORT
I've got a JS websqldump library that you can download from github as well.
This one will export the whole database. Check out the code on:
https://github.com/sdesalas/websqldump
Usage as follows
websqldump.export({
database: 'NorthwindLite',
success: function(sql) {alert(sql);}
});
Not the most elegant way, yet most convenient.
Just paste the script in chrome debugger tools then call c(), and you should get the file.
var looongSQL = "";
var x = function (options) {
if (options.n < options.sqlTables.length) {
onTheMove.openLocalDatabase().transaction(
function (tx) {
var sqlStatement = "SELECT * FROM " + options.sqlTables[options.n];
tx.executeSql(sqlStatement, [],
function (tx, rslt) {
if (rslt.rows) {
for (var m = 0; m < rslt.rows.length; m++) {
var dataRow = rslt.rows.item(m);
var _fields = [];
var _values = [];
for (col in dataRow) {
_fields.push(col);
_values.push('"' + dataRow[col] + '"');
}
looongSQL += "INSERT INTO " + options.sqlTables[options.n] + "(" + _fields.join(",") + ") VALUES (" + _values.join(",") + ");\n";
}
}
options.n++;
x(options);
}
);
});
}else
{
document.location = 'data:Application/octet-stream,' +
encodeURIComponent(looongSQL);
}
};
var c = function () {
onTheMove.openLocalDatabase().transaction(
function (transaction) {
transaction.executeSql("SELECT sql FROM sqlite_master;", [],
function (transaction, results) {
var sqlStatements = [];
if (results.rows) {
for (var i = 0; i < results.rows.length; i++) {
console.log(results.rows.item(i));
var row = results.rows.item(i);
if (row.sql != null && row.sql.indexOf("CREATE TABLE ") != -1 && row.sql.indexOf("__") == -1) {
var tableName = row.sql.replace("CREATE TABLE ", "").split(/ |\(/)[0];
sqlStatements.push('DROP TABLE IF EXISTS ' + tableName);
}if(row.sql != null && row.sql.indexOf("__") == -1){
sqlStatements.push(row.sql);}
}
}
for (var j = 0; j < sqlStatements.length; j++) {
if (sqlStatements[j] != null) {
looongSQL += sqlStatements[j] + ';\r\n';
}
}
transaction.executeSql("SELECT tbl_name from sqlite_master WHERE type = 'table'", [],
function (transaction, res) {
var sqlTables = [];
for (var k = 0; k < res.rows.length; k++) {
if (res.rows.item(k).tbl_name.indexOf("__") == -1) {
sqlTables.push(res.rows.item(k).tbl_name);
}
}
x({
sqlTables: sqlTables,
n: 0
});
});
}
);
});
};
Another version that exports it as JSON
var looongSQL = "[\n";
var stringidiedLocalStorage = JSON.stringify(JSON.stringify(localStorage));
looongSQL += "/* 1 */ " + stringidiedLocalStorage + ",\n";
var x = function (options) {
if (options.n < options.sqlTables.length) {
onTheMove.openLocalDatabase().transaction(
function (tx) {
var sqlStatement = "SELECT * FROM " + options.sqlTables[options.n];
tx.executeSql(sqlStatement, [],
function (tx, rslt) {
if (rslt.rows && rslt.rows.length > 0) {
var _fields = [];
for (var col in rslt.rows.item(0)) {
_fields.push(col);
}
var insertTableSQL = "\"INSERT INTO " + options.sqlTables[options.n] + "(" + _fields.join(",") + ") ";
looongSQL += "/* " + options.count + " */ " + insertTableSQL;
for (var m = 0; m < rslt.rows.length; m++) {
var dataRow = rslt.rows.item(m);
var _values = [];
for (var col in dataRow) {
_values.push('\'' + dataRow[col] + '\'');
}
looongSQL += "SELECT " + _values.join(",");
if (m < rslt.rows.length - 1 && (m % 499 != 0 || m == 0)) {
looongSQL += " UNION ALL ";
}
if (m % 499 == 0 && m != 0) {
options.count++;
looongSQL += "\",\r\n/* " + options.count + " */ " + insertTableSQL;
}
}
looongSQL += "\",\r\n";
options.count++;
}
options.n++;
x(options);
}
);
});
} else {
looongSQL += ']';
document.location = 'data:Application/octet-stream,' +
encodeURIComponent(looongSQL);
}
};
var c = function () {
onTheMove.openLocalDatabase().transaction(
function (transaction) {
transaction.executeSql("SELECT sql FROM sqlite_master;", [],
function (transaction, results) {
var sqlStatements = [];
var count = 2;
if (results.rows) {
for (var i = 0; i < results.rows.length; i++) {
console.log(results.rows.item(i));
var row = results.rows.item(i);
if (row.sql != null && row.sql.indexOf("CREATE ") != -1) {
var objectType = row.sql.replace("CREATE ", "").split(/ |\(/)[0];
if (row.sql.indexOf("CREATE " + objectType + " ") != -1 && row.sql.indexOf("__") == -1) {
var objectName = row.sql.replace("CREATE " + objectType + " ", "").split(/ |\(/)[0];
sqlStatements.push('/* ' + count + ' */ "DROP ' + objectType + ' IF EXISTS ' + objectName + '"');
count++;
}
if (row.sql != null && row.sql.indexOf("__") == -1) {
sqlStatements.push('/* ' + count + ' */ "' + row.sql.replace(/(\r\n|\n|\r)/gm, " ") + '"');
count++;
}
}
}
}
for (var j = 0; j < sqlStatements.length; j++) {
if (sqlStatements[j] != null) {
looongSQL += sqlStatements[j] + ',\r\n';
}
}
transaction.executeSql("SELECT tbl_name from sqlite_master WHERE type = 'table'", [],
function (transaction, res) {
var sqlTables = [];
for (var k = 0; k < res.rows.length; k++) {
if (res.rows.item(k).tbl_name.indexOf("__") == -1) {
sqlTables.push(res.rows.item(k).tbl_name);
}
}
x({
sqlTables: sqlTables,
n: 0,
count: count
});
});
}
);
});
};