How to create database in PhoneGap? - javascript

I am new in android PhoneGap.
<script type="text/javascript" charset="utf-8" src="js/cordova.js"></script>
<script type="text/javascript" charset="utf-8">
document.addEventListener("deviceready", onDeviceReady, false);
function onDeviceReady() {
var db = window.openDatabase("raddyx", "1.0", "Cordova Demo", 200000);
db.transaction(populateDB, errorCB, successCB);
}
function populateDB(tx) {
tx.executeSql('DROP TABLE IF EXISTS DEMO');
tx.executeSql('CREATE TABLE IF NOT EXISTS DEMO (id unique, data)');
tx.executeSql('INSERT INTO DEMO (id, data) VALUES (1, "First row")');
}
function errorCB(tx, err) {
alert("Error processing SQL: "+err);
}
function successCB() {
alert("success!");
}
</script>
I am using above sample code. My database name raddyx. I am unable to create database. Can you please say me how to create raddyx database in PhoneGap?
Edit - When i run it in my mobile it says Unfortunately, APP_NAME_HERE has stopped. If i remove my connection code it works fine.

You can create a database with a function like:
function queryDB() {
var db = window.openDatabase("Database", "1.0", "Cordova login", 300000);
db.transaction(inputDb, errorCB);
}
After that, you call the function inputDb which looks like:
function inputeDb(db2) {
db2.executeSql('DROP TABLE IF EXISTS login');
db2.executeSql('CREATE TABLE IF NOT EXISTS login (id_Login INTEGER PRIMARY KEY AUTOINCREMENT, UserName VARCHAR(150) NULL, UserPassword VARCHAR(100) NULL, UserHash VARCHAR(50) NULL)');
db2.executeSql('INSERT INTO login (UserName, UserPassword) VALUES ("'+uname1+'", "'+upass1+'")');
db2.executeSql('DROP TABLE IF EXISTS MDataT');
db2.executeSql('CREATE TABLE IF NOT EXISTS MDataT (id_MData INTEGER PRIMARY KEY, MData INTEGER)');
db2.executeSql('INSERT INTO MDataT (id_MData, MData) VALUES ("1", "'+MData+'")');
//alert("Username and Password - Set in DB");
location.href="serverLogin.html";
}

Related

SQLite doesn't work correctly

I'm building a project using cordova/phonegap and the Cordova-sqlite-storage plugin:
db = window.sqlitePlugin.openDatabase({name: "products.db",location: 'default'});
db.transaction(function(tx) {
tx.executeSql('CREATE TABLE IF NOT EXISTS products (id integer primary key, product_id INTEGER,title text,price text, picture text,quantite INTEGER)');
},errorc, function() {
console.log('products table created');
});
In the console I get "products table created" and everything works great, but when I try to insert anything:
db.transaction(function(tx) {
tx.executeSql('INSERT INTO products (product_id, title, quantite, price, picture) VALUES (?,?,?,?,?)',["1","1","1","1","1"]);
},errorc,function() {
$.magnificPopup.close();
showMsg(msg_product_added);
console.log('product added');
});
... and then try to see if it's there and if there are any results with the field product_id equal 1 (the entry we added above does):
db.transaction(function(tx){
tx.executeSql("SELECT count(product_id) as cnt FROM products WHERE product_id=?",1,function(tx,res){
product_total = res.rows.item(0).cnt;
if(product_total <= 0 ){
alert("the row does not exists");
}else{
alert("the row exist");
}
})
}, errorc);
I get "the row does not exists" every time. So what's wrong in the code? This is my error function that return the errors:
function errorc(error){
console.log('error: ' + error.message)
}

WebSQL - Check database for records (javascript)

I am working on a phonegap app, and have so far set-up the database to which I have the insert and delete function's working correctly.
I am now struggling on checking input values with the data in the database, so for example for now I am just simply attempting to check if any rows are returned, and if there is that will mean the user and pass entered are in the database, if no rows are returned then the user and pass is false.
I am not getting any errors from the sql statement (function errorCB), as well I did put an debug alert within the function LoginSuccess and that worked, however after removing the debug alert in the LoginSuccess function, I do not get prompted with any alerts and instead the page just refreshes.
I have removed the delete and insert functions from the code as it's relevant to this issue.
Any help will be much appreciated.
document.addEventListener("deviceready", onDeviceReady, false);
var db;
function onDeviceReady() {
db = window.openDatabase("DBkhan", "1.0", "SFDatabase", 2*1024*1024);
db.transaction(createDB, errorCB, successCB);
}
function createDB(tx) {
tx.executeSql('CREATE TABLE IF NOT EXISTS mahdi (FirstName text, LastName text, Email text, Password text)');
}
function errorCB(err) {
alert("Error processing SQL: "+err.code);
}
function successCB() {
alert("Database Ready");
}
function loginUser()
{
db = window.openDatabase("DBkhan", "1.0", "SFDatabase", 2*1024*1024);
db.transaction(loginDB, errorCB, LoginSuccess);
}
function loginDB(tx)
{
var Username = document.getElementById("username").value;
var Password = document.getElementById("password").value;
tx.executeSql("SELECT * FROM mahdi WHERE FirstName='" + Username + "' AND Password= '" + Password + "'");
} function LoginSuccess(tx, results) {
if (results.rows.length > 0) {
alert ("User and Pass Found");
}
else
{
alert ("User and Pass incorrect");
}
}
Don't worry, all fixed. See below if you'd like to see what I changed around. Seem's as though it was the missing array [] in the executesql statement and calling the renderList (changed from loginSuccessful) into the exectutesql statementent.
function loginDB(tx)
{
alert("yep yep yep");
var Username = document.getElementById("username").value;
var Password = document.getElementById("password").value;
tx.executeSql("SELECT * FROM mahdi WHERE FirstName='" + Username + "' AND Password= '" + Password + "'", [], renderList);
}
function renderList(tx,results) {
if (results.rows.length > 0) {
navigator.notification.alert("User and Pass Found");
}
else
{
navigator.notification.alert("User and Pass incorrect");
}
}

user login using cordova

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.

Error processing SQL:0 PhoneGap SQL

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

Retrieving value from database in Javascript

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

Categories

Resources