How to export (dump) WebSQL data - json

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

Related

Array Length To Limit Number of Columns

I'm attempting to limit the number of columns pulled from a data source. The source has 10 columns, I only need the first 4 columns. Seems I am confusing myself on userData and var j plus var k and var l when attempting to create an HTML table of the output.
When I use var i = 0; i < values.length; i++ and var j = 0; j < header.length; j++ with var k = 0; k < userData.length; k++ and var l = 0; l < userData[0].length; l++ the HTML output returns all the columns.
How can I limit the output to just the first 4 columns?
var sheetID = 'example';
var dataSheet = 'SOP Update ACK';
var emailHeader = 'Email Address';
var activeUser = Session.getActiveUser();
var ss = SpreadsheetApp.openById(sheetID);
function doGet(e) {
return HtmlService.createHtmlOutputFromFile('Index').setTitle('My SOP Updates');
}
function currentUser() {
if (activeUser !== '') {
return activeUser.getEmail();
} else {
return "Couldn't detect user!!!";
}
}
function getData() {
var sheetName = dataSheet;
var activeSheet = ss.getSheetByName(sheetName);
var values = activeSheet.getDataRange().getDisplayValues();
var header = values[0];
var emailIndex = header.indexOf(emailHeader);
var userData = [];
for (var i = 0; i < values.length; i++) {
if (values[i][emailIndex] == activeUser) {
userData.push(values[i]);
}
}
if (userData.length > 0) {
var tableStart = '\n<table class="table table-hover table-sm">';
var tableHead = '\n<thead>\n<tr>';
for (var j = 0; j < header.length; j++) {
tableHead = tableHead + '\n<th>' + header[j] + '</th>';
}
tableHead = tableHead + '\n</tr>\n</thead>';
var tableBody = '\n<tbody>';
for (var k = 0; k < userData.length; k++) {
tableBody = tableBody + '\n<tr>';
for (var l = 0; l < userData[0].length; l++) {
tableBody = tableBody + '\n<td>' + userData[k][l] + '</td>';
}
tableBody = tableBody + '\n</tr>\n';
}
var tableEnd = '</tbody>\n</table>';
var tableHtml = tableStart + tableHead + tableBody + tableEnd;
return tableHtml;
} else {
return '<table class="table"><tbody><tr><td>No data found.</td></tr></tbody></table>';
}
}
I got this to work:
You will have to make some minor modification to get it to work for you because I tested it on my temp data since you did not provide any
function getData() {
const ss = SpreadsheetApp.getActive();
const sh = ss.getSheetByName("Sheet0");
const [header, ...values] = sh.getDataRange().getDisplayValues();
const emailIndex = header.indexOf('Email Address');
const userData = [];
const activeUser = Session.getActiveUser();
for (let i = 0; i < values.length; i++) {
if (values[i][emailIndex] == activeUser) {
userData.push(values[i].slice(0,4));
}
}
if (userData.length > 0) {
let tableStart = '\n<table class="table table-hover table-sm">';
let tableHead = '\n<thead>\n<tr>';
for (let j = 0; j < header.length; j++) {
tableHead = tableHead + '\n<th>' + header[j] + '</th>';
}
tableHead += '\n</tr>\n</thead>';
let tableBody = '\n<tbody>';
for (let k = 0; k < userData.length; k++) {
tableBody = tableBody + '\n<tr>';
for (let l = 0; l < userData[0].length; l++) {
tableBody = tableBody + '\n<td>' + userData[k][l] + '</td>';
}
tableBody = tableBody + '\n</tr>\n';
}
let tableEnd = '</tbody>\n</table>';
let tableHtml = tableStart + tableHead + tableBody + tableEnd;
return tableHtml;
} else {
return '<table class="table"><tbody><tr><td>No data found.</td></tr></tbody></table>';
}
}

How do I email an update to the table results for specific columns that meet the criteria less than 0?

I have a table that I would like to send an email for based on the values of columns E(table below). The Columns I would like to append to the email are A,D,E,F. The Rows I would like to include are those that have dropped below 0 from column E. How do I amend my function to allow for this change?
function EmailUpdate() {
var hty = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Historical')
var data = hty.getRange("A1:F" + hty.getLastRow()).getValues().filter(([,e], i) => i == 0 || e < 0);
var TABLEFORMAT = 'cellspacing="2" cellpadding="2" dir="ltr" border="1" style="width:100%;table-layout:fixed;font-size:10pt;font-family:arial,sans,sans-serif;border-collapse:collapse;border:1px solid #ccc;font-weight:normal;color:black;background-color:white;text-align:left;text-decoration:none;font-style:normal;'
var htmltable = '<table ' + TABLEFORMAT + ' ">';
for (row = 0; row < data.length; row++) {
htmltable += '<tr>';
for (col = 0; col < data[row].length; col++) {
if (data[row][col] === "" || 0) {
htmltable += '<td>' + 'None' + '</td>';
} else
if (row === 0) {
htmltable += '<th>' + data[row][col] + '</th>';
} else {
htmltable += '<td>' + data[row][col] + '</td>';
}
}
htmltable += '</tr>';
}
htmltable += '</table>';
Logger.log(data);
Logger.log(htmltable);
MailApp.sendEmail(Session.getActiveUser().getEmail(), 'Email Report', '' ,{
htmlBody: htmltable
})
}
Replace:
var data = hty.getRange("A1:F" + hty.getLastRow()).getValues().filter(([,e], i) => i == 0 || e < 0);
With:
var data = hty.getRange("A1:F"+hty.getLastRow()).
getDisplayValues().
map(([a,,,d,e,f]) => [a,d,e,f]).
filter((r,i)=>r[2].includes("-") || i==0 );
References:
map
filter

GAS - Script execution time too long / Workaround?

I have a script that takes more than 5 minutes to execute. So it will be aborted after 5 minutes with the information that the execution time is too long.
Now I am looking for a solution to handle this. In the following example I would like to interrupt when var = i has reached a value of 300 and then continue with i = 301. Is this an option for a workaround? If so, how has the code to be adapted?
var xy = 1100;
for (var = i; i<= xy; i++){
{
do_some_stuff();
}
}
In practice my code is the following....and the loop is starting with for(var i = 3; i <= lastrow +1; i++) lastrow has a value of 1500.
function Create_geodata()
{
var Geodata = getSheetById(1702838837);
var Geojson_Data = getSheetById(1515926044);
var Control_Panel = getSheetById(1102907697);
Geodata.getRange('I4').setValue('Yes');
var Hyperlink_Geodata = Control_Panel.getRange('O18').getValue();
var document_missing_ID = Control_Panel.getRange('O24').getValue();
var Umap_Hyperlink = Control_Panel.getRange('L20').getValue();
var umap_zoom = Control_Panel.getRange('N22').getValue();
var Own_ID_Sort_Setting = Control_Panel.getRange('O30').getValue();
var Own_ID_Sort = Control_Panel.getRange('M32').getValue();
var Threshold_Altitude = Control_Panel.getRange('N28').getValue();
var Automatic_Altitude_Removal = Control_Panel.getRange('O26').getValue();
var Cat_A = Control_Panel.getRange('C36').getValue();
var Cat_B = Control_Panel.getRange('C38').getValue();
var Cat_C = Control_Panel.getRange('C40').getValue();
RESET_Geodata(); //Clear data before proceed
if (Own_ID_Sort_Setting)
{standard_sort_column = Own_ID_Sort}
else
{standard_sort_column = "name"}
var data = Geojson_Data.getDataRange().getValues();
var col1 = data[0].indexOf(standard_sort_column) + 1;
var col2 = data[0].indexOf('coordinates') + 1;
var col3 = data[0].indexOf('name') + 1;
var col4 = data[0].indexOf('description') + 1;
var col1_Char = columnToLetter(col1); //last row of column where sort-criteria is located
var col2_Char = columnToLetter(col2);
var col3_Char = columnToLetter(col3);
var col4_Char = columnToLetter(col4);
var lastrow_col1 = Geojson_Data.getRange(col1_Char + ':' + col1_Char).getValues();
lastrow_col1 = lastrow_col1.filter(String).length;
var lastrow = Geojson_Data.getLastRow();//last row of complete sheet
var lc = Geojson_Data.getLastColumn(); //last column
var lc_Char = columnToLetter(lc);
var dc = 0;
Geojson_Data.getRange('N1').setValue(col1);
if (!document_missing_ID)
{
for(var t = 2; t <= lastrow; t++)
{
if (Geojson_Data.getRange(t,col1).getValue() == "")
{
Geojson_Data.deleteRow(t);
}
}
}
else
{
for(var t = 2; t <= lastrow; t++)
{
if (Geojson_Data.getRange(t,col1).getValue() == "")
{
dc++;
var formattedNumber = ("000" + dc).slice(-4);
Geojson_Data.getRange(t,col1).setValue('ZZ_' + formattedNumber);
}
}
}
Geojson_Data.getRange('A2:' + lc_Char + lastrow).sort(col1);
Geojson_Data.getRange(col1_Char + 2 + ':' + col1_Char + lastrow).copyTo(Geodata.getRange('A3:A' + lastrow),{contentsOnly: true});
Geojson_Data.getRange(col2_Char + 2 + ':' + col2_Char + lastrow).copyTo(Geodata.getRange('F3:F' + lastrow),{contentsOnly: true});
Geojson_Data.getRange(col3_Char + 2 + ':' + col3_Char + lastrow).copyTo(Geodata.getRange('B3:B' + lastrow),{contentsOnly: true});
Geojson_Data.getRange(col4_Char + 2 + ':' + col4_Char + lastrow).copyTo(Geodata.getRange('D3:D' + lastrow),{contentsOnly: true});
var geodata_sorted = '';
var route_length = 0;
for(var i = 3; i <= lastrow +1; i++)
{
var pr = 0;
var fl = false;
var distance_neighbour_points = 0;
var Ar = Geodata.getRange('F' + i).getValue();
Ar = Ar.split(',');
var Ar_Anz = Ar.length - 1;
for(var b = 0; b <= Ar_Anz; b=b+2)
{
if ((Ar_Anz - b) != 0)
{
var E_Lat = Ar[b];
var E_Lon = Ar[b + 1];
if (fl)
{
var A_Lat = Ar[b - 2];
var A_Lon = Ar[b - 1];
distance_neighbour_points = distVincenty(A_Lat, A_Lon, E_Lat, E_Lon);
if (Automatic_Altitude_Removal && (distance_neighbour_points > Threshold_Altitude))
{
b++;
E_Lat = Ar[b];
E_Lon = Ar[b + 1];
A_Lat = Ar[b - 3];
A_Lon = Ar[b - 2];
}
route_length = route_length + distVincenty(A_Lat, A_Lon, E_Lat, E_Lon);
}
pr++;
fl = true;
}
geodata_sorted = geodata_sorted + E_Lat + ',' + E_Lon;
if ((Ar_Anz - b) < 2)
{
}
else
{
geodata_sorted = geodata_sorted + ',';
}
if ((Ar_Anz - b) < 2)
{
pr = parseInt(pr / 2) * 2 + 1;
var Ay = geodata_sorted.split(',');
var Geo_Mitte_Lon = Ay[pr - 1];
var Geo_Mitte_Lat = Ay[pr];
var googlemaps = 'https://maps.google.com/?q=' + Geo_Mitte_Lat + ',' + Geo_Mitte_Lon;
var umap = 'https://umap.openstreetmap.fr/de' + '/map/' + Umap_Hyperlink + '#' + umap_zoom + '/' + Geo_Mitte_Lat + '/' + Geo_Mitte_Lon;
Geodata.getRange(i, 3).setValue(route_length / 1000);
Geodata.getRange(i, 6).setValue(geodata_sorted);
Geodata.getRange(i, 7).setValue(googlemaps);
Geodata.getRange(i, 8).setValue(umap);
//Verlinkung
if (Hyperlink_Geodata)
{
var displayName1 = Geodata.getRange(i,1).getValue();
var displayName2 = Geodata.getRange(i,2).getValue();
Geodata.getRange(i,1).setFormula('=HYPERLINK(\"' + googlemaps + '\";\"' + displayName1 + '\")');
Geodata.getRange(i,2).setFormula('=HYPERLINK(\"' + umap + '\";\"' + displayName2 + '\")');
}
geodata_sorted = '';
route_length = 0;
}
}
//Set categories Cat_A,B,C...
var description_content = Geodata.getRange(i,4).getValue();
var regExpA = new RegExp('/*' + Cat_A, 'gi');
var regExpB = new RegExp('/*' + Cat_B, 'gi');
var regExpC = new RegExp('/*' + Cat_C, 'gi');
var compareA = regExpA(description_content);
var compareB = regExpB(description_content);
var compareC = regExpC(description_content);
if (compareC == Cat_C) Geodata.getRange(i,5).setValue(Cat_C);
if (compareB == Cat_B) Geodata.getRange(i,5).setValue(Cat_B);
if (compareA == Cat_A) Geodata.getRange(i,5).setValue(Cat_A);
}
SpreadsheetApp.getActiveSpreadsheet().setActiveSheet(Geodata);
Geodata.getRange('I4').setValue('No');
}

Google Apps Script to remove hangouts links from calendar events

I have successfully accessed a Google calendar event and can change the color, but I'm stuck when it comes to removing the hangouts link.
I'm attempting to use code to automatically remove the hangouts links when I am the meeting originator and have not changed the hangout name, but I'm not having any success in actually changing the link.
Any help greatly appreciated.
function removehangout() {
var calendarId = 'primary';
//var calendars = CalendarApp.getOwnedCalendarsByName('Mirage ELDRIDGE');
var now = new Date();
// Determines how many events are happening in the next 24 hours x 1 days.
var now = new Date();
var endr = new Date(now.getTime() + (1 * 24 * 60 * 60 * 1000));
var events2 = CalendarApp.getDefaultCalendar().getEvents(now, endr);
Logger.log('Number of events: ' + events2.length);
var events = Calendar.Events.list(calendarId, {
timeMin: now.toISOString(),
singleEvents: true,
orderBy: 'startTime',
maxResults: 5
});
if (events.items && events.items.length > 0) {
for (var i = 0; i < events.items.length; i++) {
var event1 = events.items[i];
var d = event1.description;
var ttitle = event1.summary;
var whoby = event1.creator.email;
Logger.log(ttitle + ' by: ' + whoby);
if(whoby.indexOf('mirage.eldridge') != -1){
Logger.log(ttitle + '--> was by mirage');
var hangoutname = event1.hangoutLink;
Logger.log(ttitle + '--> hangout link name --> ' + hangoutname);
if (hangoutname != null) {
if (hangoutname.indexOf('mirage-eldridge') != -1){
//delete this link here
Logger.log(ttitle + '--> remove hangout');
//event.setHangoutLink(null);
//var idno = event.iCalUID
//CalendarApp.getEventSeriesById(idno)
event1.HangoutLink = null;
Logger.log(ttitle + '... ' + event1.hangoutLink);
Logger.log(event1.iCalUID);
//event.setcolorId('11');
var event2 = Calendar.Events.get(calendarId, event1.id)
event2.colorId = 9;
event2.hangoutLink = 'fred';
//Calendar.Events.patch(event2,calendarId,event1.id);
Calendar.Events.update(event2,calendarId,event1.id);
}
} else {
Logger.log(ttitle + ' -- do not remove ' + hangoutname);
}
}
if (!d)
d = '';
//var foundlinkyes = d.indexOf('HangoutLink');
//var actuallink = event.hangoutLink;
//var hasrlink = 'True';
//if (!actuallink) {
//Logger.log(ttitle + ' no link found');
//hasrlink = "False";
//}
//Logger.log('desc: ' + ttitle + '-- foundyes: ' + foundlinkyes);
//if (foundlinkyes == -1 && hasrlink == 'True'){
//if (event.hangoutLink && (d.indexOf('Hangout: ')== -1)){
//Logger.log (event.summary + ' - ' + event.hangoutLink + ' - ' + event.description);
//Logger.log(ttitle + ' added this ' + event.hangoutLink);
//event.description = 'HangoutLink: ' + event.hangoutLink + '\n\n' + d;
//Calendar.Events.update(event, calendarId, event.id);
//foundlinkyes = 0;
//hasrlink = 'True';
//}
//}
}
} else {
Logger.log('No events found.');
}
}

else condition in script with sqlite

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