I created an android app using html5 and phonegap and
I have a problem in inserting data into database..
this is my code
document.addEventListener("deviceready", onDeviceReady(), false);
var db;
function onDeviceReady(){
db = window.openDatabase("Libsys", "2.0", "LibraryDB", 200000); //will create database Dummy_DB or open it
db.transaction(populateDB, errorCB, successCB);
}
function populateDB(tx) {
tx.executeSql('CREATE TABLE IF NOT EXISTS Borrowinfo(id INTEGER PRIMARY KEY AUTOINCREMENT, IDno TEXT NOT NULL, Name TEXT NOT NULL, course TEXT NOT NULL, author TEXT NOT NULL, title TEXT NOT NULL, date_start TEXT NOT NULL, date_return TEXT NOT NULL)');
}
function queryDB(tx){
tx.executeSql('SELECT * FROM Borrowinfo', [], querySuccess, errorCB);
}
function querySuccess(tx,results){
var len = results.rows.length;
for (var i = 0; i < len; i++) {
var row = results.rows.item(i);
$("#Lists").append("<li><a href='#'>"+row['Name']+" "+row['course']+"</a></li>");
}
$("#Lists").listview("refresh");
}
function SaveContacts(idno,fullname,course,author,title,dstart,dreturn){
//alert(""+idno+" "+fullname+"");
db.transaction(function(tx){
var idno = document.getElementById("idno").value;
var fullname = document.getElementById("names").value;
var course = document.getElementById("course").value;
var author = document.getElementById("author").value;
var title = document.getElementById("title").value;
var dstart = document.getElementById("dstart").value;
var dreturn = document.getElementById("dreturn").value;
tx.executeSql('INSERT INTO Borrowinfo(IDno,name,course,author,title,date_start,date_return) VALUES (?,?,?,?,?,?,?)', [idno,fullname,course,author,title,dstart,dreturn], querySuccess);
alert("Record Save!");
});
}
function errorCB(err) {
alert("Error processing SQL: "+err.code);
}
function successCB() {
db.transaction(queryDB,errorCB);
}
im having an error in the function querySuccess.. the error message is (undefined is not a function querySuccess)
Please, correct me and also help me to fixed the error...
thank you..
Related
i'm gettin sql processing error sql:underfined here.Here i'm check whether the login form matched with the database called student and if there is a matched then an alert popup with welcome message and transfer to the next page.How do i fix the code?
document.addEventListener("deviceready", onDeviceReady, false);
var db;
function onDeviceReady() {
db = window.openDatabase("Database", "1.0", "Student",2*1024*1024);
db.transaction(createDB, errorCB, successCB);
}
function loginForm(){
db.transaction(checkDB, errorCB);
$.mobile.changePage("#page5",{reverse:false,transition:"slide"});
return false;
}
function checkDB(tx){
var _matric=$("[name='matric']").val();
var _password=$("[name='password']").val();
var sql ='select * from STUDENT where matric='+_matric+' and password='+_password+'';
tx.executeSql(sql,[],successLoginDB,errorCB);
}
function successLoginDB(tx,results){
var len = results.rows.length;
var _name =$("[name='name']").val();
if (len==1) {alert("Welcome "+_name);}
}
First you code is vulnerable to SQL Injection, fix it using args:
function loginForm(){
db.transaction(checkDB, errorCB);
$.mobile.changePage("#page5",{reverse:false,transition:"slide"});
return false;
}
function checkDB(tx){
var matric=$("[name='matric']").val();
var password=$("[name='password']").val();
var sql ='select * from STUDENT where matric = ? and password = ?';
tx.executeSql(sql,[matric, password],successLoginDB,errorCB);
}
function successLoginDB(tx,results){
var len = results.rows.length;
var name =$("[name='name']").val();
if (len==1) {alert("Welcome "+name);}
}
About error; I'm sure you are trying to use webSQL before cordova loads. You need wait for "DOM Ready" (for read text inputs) and "deviceready" for access to WebSQL:
document.addEventListener("deviceready", onDeviceReady, false);
var onDeviceReady = function () {
// Start here.
}
Please, post more info.
Im trying out and copied code from here:
http://luthfihariz.wordpress.com/2011/10/23/android-sqlite-phonegap-jquerymobile/
To succeed with a sample I'm working on just to learn this.
I have a link to my complete index.html on pastebin.
Please, correct me and also help me finding this errror.
Link to Pastebin here
I didn't have a lot of time, and it's soon xmas :) But.. :) I did write you a working example with your code as a starter.
Using Cordova version 2.2.0
Using PhoneGap to compile
I did test it on an android device
I did change some things here and there, but I used the code frome here as a reference.
document.addEventListener("deviceready", onDeviceReady, false);
var db = "";
function populateDB(tx) {
tx.executeSql('DROP TABLE IF EXISTS SoccerPlayer');
tx.executeSql('CREATE TABLE IF NOT EXISTS SoccerPlayer (Name TEXT NOT NULL, Club TEXT NOT NULL)');
tx.executeSql('INSERT INTO SoccerPlayer(Name,Club) VALUES ("Alexandre Pato", "AC Milan")');
tx.executeSql('INSERT INTO SoccerPlayer(Name,Club) VALUES ("Van Persie", "Arsenal")');
}
function queryDB(tx) {
tx.executeSql('SELECT * FROM SoccerPlayer', [], querySuccess, errorCB);
}
function querySuccess(tx,result){
var playerlist = document.getElementById("SoccerPlayerList");
var players = "";
alert("The show is on");
var len = result.rows.length;
for (var i=0; i<len; i++){
alert(result.rows.item(i).Name + result.rows.item(i).Club);
players = players + '<li><p class="record">'+result.rows.item(i).Name+'</p><p class="small">Club '+result.rows.item(i).Club+'</p></li>';
}
playerlist.innerHTML = players;
$("#SoccerPlayerList").listview("refresh");
}
function errorCB(err) {
alert("Error processing SQL: "+err.code);
}
function successCB() {
db.transaction(queryDB, errorCB);
}
function onDeviceReady() {
db = window.openDatabase("Database", "1.0", "PhoneGap Demo", 200000);
db.transaction(populateDB, errorCB, successCB);
}
I am new to mobile application development with PhoneGap. I have created a form to add and show name, address and phone number of a student in SQLite database. But the problem is I don't know to retrieve and display the values in the text boxes.
<!DOCTYPE HTML>
<html>
<head>
<title>Contact Example</title>
<script type="text/javascript" charset="utf-8" src="phonegap-1.4.1.js"></script>
<script type="text/javascript" charset="utf-8">
document.addEventListener("deviceready", onDeviceReady, false);
function onDeviceReady() {
var db = window.openDatabase("Database", "1.0", "PhoneGap Demo", 200000);
db.transaction(populateDB, errorCB, successCB);
}
function populateDB(tx) {
tx.executeSql('CREATE TABLE IF NOT EXISTS DEMO (sname ,saddress ,sphone)');
}
function errorCB(tx, err) {
alert("Error processing SQL: "+err);
}
// Transaction success callback
//
function successCB() {
alert("success!");
}
function add(tx){
var name=document.getElementById('n');
var address=document.getElementById('a');
var phone=document.getElementById('p');
tx.executeSql('INSERT INTO DEMO (sname ,saddress ,sphone) VALUES ('"+name+"','"+address+"','"+phone+"')');
//tx.executeSql('INSERT INTO DEMO (id, data) VALUES (2, "Second row")');
}
function show(tx){
var name=document.getElementById('n');
tx.executeSql('SELECT * FROM DEMO WHERE (sname='"+name+"')');
document.f.n.value=name;
document.f.a.value=//??;
document.f.p.value=//??;
}
</script>
</head>
<body>
<form name="f" method="get" action="">
Name :<input type="text" id="n" size="10"></input><br>
Add :<input type="text" id="a" size="10"></input><br>
Phone :<input type="text" id="p" size="10"></input><br>
<input type="button" value="Add" onClick="add()">
<input type="button" value="Show" onClick="show()">
</form>
</body>
</html>
document.addEventListener("deviceready", onDeviceReady, false);
function onDeviceReady()
{
alert("onDeviceReady called");
}
function populateDB(tx)
{
tx.executeSql('CREATE TABLE IF NOT EXISTS DEMO (sname ,saddress ,sphone)');
var name=document.getElementById('n');
var address=document.getElementById('a');
var phone=document.getElementById('p');
tx.executeSql('INSERT INTO DEMO (sname ,saddress ,sphone) VALUES ('"+name.value+"','"+address.value+"','"+phone.value+"')');
}
function errorCB(tx, err)
{
alert("Error processing SQL: "+err);
}
// Transaction success callback
//
function successCB()
{
alert("success!");
}
function add()
{
var db = window.openDatabase("Database", "1.0", "PhoneGap Demo", 200000);
db.transaction(populateDB, errorCB, successCB);
}
for more see link here
//show data from db
// Transaction success callback
function show()
{
var db = window.openDatabase("Database", "1.0", "PhoneGap Demo", 200000);
db.transaction(queryDB, errorCB);
}
// Query the database
function queryDB(tx)
{
tx.executeSql('SELECT * FROM DEMO', [], querySuccess, errorCB);
}
// Query the success callback
function querySuccess(tx, results)
{
var len = results.rows.length;
console.log("DEMO table: " + len + " rows found.");
for (var i=0; i<len; i++){
console.log("Row = " + i + " sname = " + results.rows.item(i).sname + " saddress = " + results.rows.item(i).saddress);
}
}
// Transaction error callback
function errorCB(err)
{
console.log("Error processing SQL: "+err.code);
}
Inside your code for save call
db.transaction(populateDB, errorCB, successCB)
The function will return to
function populateDB(tx) {
var rr=escape(JSON.stringify(onedata));//here onedata is data you want to save I use json data here.
tx.executeSql('CREATE TABLE IF NOT EXISTS LeadInfo (data)');
tx.executeSql('INSERT INTO LeadInfo (data) VALUES ("'+ rr +'")');
alert("Insert")
}
function errorCB(tx, err) {
//alert("Error processing SQL Insert: "+err);
}
function successCB() {
// alert("success!");
}
For retrieval you can use following:
function queryDB(tx) {
tx.executeSql('SELECT * FROM LeadInfo', [], querySuccess, errorCB);
}
function querySuccess(tx, results) {
var tablereport="";
if (results != null && results.rows != null) {
for (var i = 0; i < results.rows.length; i++) {
var row =unescape(results.rows.item(i).data);
var obj = JSON.parse(row);
tablereport+='<a href="#"><span style="font-size:18px; font-weight:400; padding:10px 0px 10px 0px;">'+JSON.stringify(obj.lead_name)+'</span><span style="padding: 10px 16px;width: 100px;float: right;margin-top: -33px;margin-right: -80px;font-size:14px"></span><br>';
tablereport+='</li>';
tablereport+='</li>';
}
}
}
function errorCB(err) {
alert("Error processing SQL Retrive: "+err.code);
}
I'm currently using phonegap to create and ios app.
While getting familiar to the sql javascript interactions I seem to have created 10 versions of the same named database file.
I'm currently using the following creation code (from the phonegap wiki)
var mydb=false;
// initialise the database
initDB = function() {
try {
if (!window.openDatabase) {
alert('not supported');
} else {
var shortName = 'phonegap';
var version = '1.0';
var displayName = 'PhoneGap Test Database';
var maxSize = 65536; // in bytes
mydb = openDatabase(shortName, version, displayName, maxSize);
}
} catch(e) {
// Error handling code goes here.
if (e == INVALID_STATE_ERR) {
// Version number mismatch.
alert("Invalid database version.");
} else {
alert("Unknown error "+e+".");
}
return;
}
}
// db error handler - prevents the rest of the transaction going ahead on failure
errorHandler = function (transaction, error) {
// returns true to rollback the transaction
return true;
}
// null db data handler
nullDataHandler = function (transaction, results) { }
my problem is that I'm unsure how to check if the database exists before creating it or how to create it only once per device?
and secondly how can i drop all these databases that have been created.
transaction.executeSql('DROP DATABASE phonegap;');
does not seem to drop anything.
Thanks
Please try following code. it is not creating multiple database files, just cross verify by visiting location -/Users/{username}/Library/Application Support/iPhone Simulator/4.3/Applications/{3D5CD3CC-C35B-41B3-BF99-F1E4B048FFFF}/Library/WebKit/Databases/file__0
This is sqlite3 example which cover create, insert, delete and drop queries on Table.
<!DOCTYPE html>
<html>
<body style="font: 75% Lucida Grande, Trebuchet MS">
<div id="content"></div>
<p id="log" style="color: gray"></p>
<script>
document.getElementById('content').innerHTML =
'<h4>Simple to do list</h4>'+
'<ul id="results"></ul><div>Handle Database in Phonegap</div>'+
'<button onclick="newRecord()">new record</button>'+
'<button onclick="createTable()">create table</button>' +
'<button onclick="dropTable()">drop table</button>';
var db;
var log = document.getElementById('log');
db = openDatabase("DBTest", "1.0", "HTML5 Database API example", 200000);
showRecords();
document.getElementById('results').addEventListener('click', function(e) { e.preventDefault(); }, false);
function onError(tx, error) {
log.innerHTML += '<p>' + error.message + '</p>';
}
// select all records and display them
function showRecords() {
document.getElementById('results').innerHTML = '';
db.transaction(function(tx) {
tx.executeSql("SELECT * FROM Table1Test", [], function(tx, result) {
for (var i = 0, item = null; i < result.rows.length; i++) {
item = result.rows.item(i);
document.getElementById('results').innerHTML +=
'<li><span contenteditable="true" onkeyup="updateRecord('+item['id']+', this)">'+
item['id']+' '+item['text'] + '</span> x</li>';
}
});
});
}
function createTable() {
db.transaction(function(tx) {
tx.executeSql("CREATE TABLE Table1Test (id REAL UNIQUE, text TEXT)", [],
function(tx) { log.innerHTML = 'Table1Test created' },
onError);
});
}
// add record with random values
function newRecord() {
var num = Math.round(Math.random() * 10000); // random data
db.transaction(function(tx) {
tx.executeSql("INSERT INTO Table1Test (id, text) VALUES (?, ?)", [num, 'Record:'],
function(tx, result) {
log.innerHTML = 'record added';
showRecords();
},
onError);
});
}
function updateRecord(id, textEl) {
db.transaction(function(tx) {
tx.executeSql("UPDATE Table1Test SET text = ? WHERE id = ?", [textEl.innerHTML, id], null, onError);
});
}
function deleteRecord(id) {
db.transaction(function(tx) {
tx.executeSql("DELETE FROM Table1Test WHERE id=?", [id],
function(tx, result) { showRecords() },
onError);
});
}
// delete table from db
function dropTable() {
db.transaction(function(tx) {
tx.executeSql("DROP TABLE Table1Test", [],
function(tx) { showRecords() },
onError);
});
}
</script>
</body>
</html>
And about Droping Database...
Does not seem meaningful for an embedded database engine like SQLite. To create a new database, just do sqlite_open(). To drop a database, simply delete the file.
thanks,
Mayur
Manually deleting the SQLite database from the Library worked for me. Thanks for the precious tip.
I am new to Android-Phonegap dev. I am creating a project using Eclipse in Windows XP.
I am using sqlite database. I saw the sample code in the docs. But I'm not able to execute this example. I am not getting the required results.
Suppose I want to get all the entries in the table demo in tabular format, HTML. What will the code be in index.html? For that, what is the procedure and what is the step by step procedure for doing this? Or else any better tutorials which help me to do this?
Thanks in Advance
Dnyan.
in main.js you add this
rowsDataHandler = function(transaction, results) {
// Handle the results
var html = "<ul>";
for (var i=0; i<results.rows.length; i++) {
var row = results.rows.item(i);
html += '<li>'+row['data']+'</li>\n';
}
html +='</ul>';
document.getElementById("mydata").innerHTML = html;
}
// load the currently selected icons
loadRows = function(db) {
try {
db.executeSql('SELECT * FROM DEMO',[], rowsDataHandler, errorCB);
} catch(e) {alert(e.message);}
}
in index.html you add this row inside body
<div id="mydata"></div>
One thing to bear in mind is that if you aren't testing the application on a device or in an emulator, but rather in a browser like Chrome or Safari,
document.addEventListener("deviceready", onDeviceReady, false);
won't work. What I've done is to comment out this line and just to put in a call to
onDeviceReady();
When I then test in the emulator I uncomment the "document…" line and comment out
onDeviceReady();
**html**
<input id="show" type="button" value="Show">
**js**
function globalError(tx, error)
{
alert("Error: " + error.message);
}
var db = window.openDatabase('TabOrder', '', 'Bar Tab Orders', 2500000);
db.transaction(function(tx) {
tx.executeSql('DROP TABLE IF EXISTS SubmiteData;', null, null, globalError);
tx.executeSql('CREATE TABLE IF NOT EXISTS SubmiteData (SubmiteDataId integer
primary key, UserId text, AuthNo number, LocId number,ProdId number,
CardId number, OrgLat text, OrgLng text, OrgTime text)',
null,
function()
{
SubmiteData("USER1",12345678,23434, 21212, 220232,
"9", "45", "23/06/2014");
},
globalError);
});
function SubmiteData(UserId, AuthNo, LocId,ProdId, CardId, OrgLat, OrgLng, OrgTime){
db.transaction(function(tx){
tx.executeSql('INSERT INTO SubmiteData(UserId, AuthNo, LocId, ProdId, CardId,
OrgLat, OrgLng, OrgTime) VALUES (?,?,?,?,?,?,?,?)', [UserId, AuthNo, LocId,
ProdId, CardId, OrgLat, OrgLng, OrgTime],
null,
globalError
);
});
}
function read(UserId, AuthNo, LocId,ProdId, CardId, OrgLat, OrgLng, OrgTime){
db.transaction(function(tx) {
tx.executeSql('SELECT * FROM SubmiteData',
[],
function(tx, results)
{
for (var i=0; i<results.rows.length; i++)
{
var row=results.rows.item(i);
// alert("Id: " + row['UserId']);
var stringout = "LocId: " + row['LocId'] + "\n";
alert(stringout);
}
},
globalError
);
});
};
$(function()
{
$('#show').click(read);
});
this is the method to connect to a db using javascript
db = openDatabase("bprueba","1.0","Prueba_db",5*1023*1024);
SQL Statement Error Callback Reference