I'm working on a Titanium app and have build a function to run sqlite database queries and return a result set (array).
I'll not bother going too far into Titaniums details as it shouldnt make too much difference to the issue I'm facing.
Basically any query can be executed using this function, so naturally once its executed you need an array of data which corresponds to certain database column names. This is where I'm having an issue. With the way the titanium system works, I need to push the results into a results array, like so:
var resultSet = conn.execute('SELECT * FROM some_table WHERE parent = ?', parent);
if (resultSet.isValidRow()) {
result = {
id: resultSet.fieldByName('id'),
name: resultSet.fieldByName('name'),
parent: resultSet.fieldByName('parent'),
order: resultSet.fieldByName('order')
};
}
Ok, so thats all ok. But its not dynamic enough. What happens when you want to select from a different table, with different fields. id, name, parent and order are obviously not going to work.
What I'm trying to do is take an array (which I've already got) and use the values as their names, like so:
var resultSet = conn.execute(<!-- SQL IS IN HERE -->);
var fieldCount = resultSet.fieldCount();
var fields = [];
for(i=0;i<fieldCount;i++) {
fields.push(resultSet.fieldName(i));
};
// At this point we have an array 'fields' which contains all the field names.
var results = [];
while (resultSet.isValidRow()) {
results.push({
// START OF PROBLEM
for(i=0; i < fields.length; i++)
{
fields[i]: resultSet.fieldByName(fields[i]);
}
// END OF PROBLEM
});
resultSet.next();
};
resultSet.close();
The commented start/end above shows the problem code. I realise its wrong, however cant figure out how it should be. Lets say the field array contains 'id' and 'name', I need variables to cover the two of them, but they must be dynamic - I want to avoid having to create a new javascript function for every table.
I should point out that I'm a PHP guy and my experience in JS is very limited. I've been using this as an opportunity to learn but just cant get my head around this one! Really sorry if its not explained clearly enough and hope that a JS guru can lend a hand here!
Cheers