Skip to content

Instantly share code, notes, and snippets.

@mattlanham
Created October 1, 2010 15:42
Show Gist options
  • Save mattlanham/606367 to your computer and use it in GitHub Desktop.
Save mattlanham/606367 to your computer and use it in GitHub Desktop.
// This JS file will hold all functions relating to people
Ti.include('includes/phpjs.js');
function Person() {
// Class variables
this.id = '';
this.name = '';
this.budget = '';
this.created = '';
this.updated = '';
/*
getById
This will return a person based on their ID
*/
this.getById = function(id) {
// Open the DB
var db = Titanium.Database.open('gifterapp');
// Get the person based on id
var person = db.execute("SELECT * FROM PEOPLE WHERE ID = ? LIMIT 1", id);
if(person.getRowCount() == 1){
// Set all of this classes variables to the data
this.id = person.fieldByName('id');
this.name = person.fieldByName('name');
this.budget = person.fieldByName('budget');
this.created = person.fieldByName('created');
this.updated = person.fieldByName('updated');
// Close the DB
db.close();
// Return result
return true;
}else{
// Close the DB
db.close();
// Return result
return false;
}
// Close the DB
db.close();
};
/*
getAll
This will return all people in the DB
*/
this.getAll = function() {
// Set an array
var rows = [];
var rowCount = 0;
// Open the DB
var db = Titanium.Database.open('gifterapp');
// Get all rows
var person = db.execute("SELECT * FROM PEOPLE");
// Loop through results
if(person.getRowCount() > 0){
while (person.isValidRow())
{
var thisPerson = new Person();
thisPerson.getById(person.fieldByName('id'));
rows[rowCount] = thisPerson;
rowCount++;
person.next();
}
// Close the DB
db.close();
// Return the result
return rows;
}else{
// Close the DB
db.close();
// Return the result
return false;
}
};
/*
countAll
This function will simply return the integer of how many rows there are
in the DB
*/
this.countAll = function() {
// Open the DB
var db = Titanium.Database.open('gifterapp');
// Get the person based on id
var people = db.execute("SELECT * FROM PEOPLE");
// Return number of rows
return people.getRowCount();
};
/*
Save
This function will save the information to the database
*/
this.save = function() {
// Open the DB
var db = Titanium.Database.open('gifterapp');
if(this.id == 0 || this.id == ''){
// This is a new user
this.created = date('Y-m-d H:i:s');
this.updated = date('Y-m-d H:i:s');
db.execute("INSERT INTO PEOPLE (NAME, BUDGET, CREATED, UPDATED) VALUES (?, ?, ?, ?)", this.name, this.budget, this.created, this.updated);
}else{
// Update existing record
this.updated = date('Y-m-d H:i:s');
db.execute("UPDATE PEOPLE SET NAME = ?, BUDGET = ?, UPDATED = ? WHERE ID = ?", this.name, this.budget, this.updated, this.id);
}
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment