Question

I've looked around everywhere, but I can't seem to find exactly what I'm trying to do. It should be fairly simple...

I have a db table set up like this:

var db = Ti.Database.open('playerInfo.db');
db.execute('CREATE TABLE IF NOT EXISTS playersTable (id INTEGER PRIMARY KEY, name TEXT NOT NULL, "50" INTEGER, "25" INTEGER )');

I have two buttons with an assigned value of 25, and 50, respectively. Each button has a "value" key, where I assign their values. I am trying to accomplish three things: When a button is pressed, find the column of corresponding value. increase the value of this column by 1. Retrieve the new value and console log it.

This is what my code looks like when a button is pressed:

var rows = db.execute("SELECT '" + button.value + "' FROM playersTable WHERE name= '" + owner + "'");

var imagesString = rows.fieldByName(button.value);
Ti.API.debug(imagesString)

This is all in a click event listener where the variable "owner" is passed in as a string.

This is the error I get:

message = "Attempted to access unknown result column 25";

I don't have too much experience with sql, so I'm not sure what I'm doing right and what I'm doing wrong. Any help is appreciated!

Thanks.

Was it helpful?

Solution

I'm not sure quite exactly what the problem is, but the following works for me. Note that the "?" variable substitution syntax makes sure that the values are quoted properly for MySQL:

button = e.source;
db = Titanium.Database.open('test');
var rows = db.execute("SELECT * FROM playersTable WHERE name= ?", "foo");
// Theoretically this should be returning a single row. For other results,
// we would loop through the result set using result.next, but here just check if
// we got a valid row.
if (rows.isValidRow()) {
    var imagesString = rows.fieldByName(button.value);
    var id = rows.fieldByName('id');
    imagesString = imagesString + 1;
    Ti.API.info("id = " + id + " val = " + imagesString);
    // The ? substitution syntax doesn't work for column names, so we 
    // still need to stick the button value into the query string.
    db.execute('UPDATE playersTable set "' + button.value +'"= ? where id = ?', imagesString, id);
}
else
{
    Ti.API.info("Row not found.");
}
db.close();

If you get the row not found error, it's possible your data isn't getting inserted properly in the first place. Here's how I inserted my test row for player "foo":

db.execute('insert into playersTable (name, "50", "25") values (?,?,?)', 'foo', 0, 0);

I think this should solve your problem. Let me know if this doesn't work for you.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top