I’m trying to make my code better by being more specific with the SQL queries:
The following code works and I can work with the results. But probably not the most efficient:
function queryDB(tx) {
tx.executeSql('SELECT * FROM foo', [], querySuccess);
}
function querySuccess(tx, results) {
console.log(results.rows.item(0).name);
}
OUTPUT: JOHN
So when I try:
function queryDB(tx) {
tx.executeSql('SELECT id FROM foo WHERE id = 1', [], querySuccess);
}
function querySuccess(tx, results) {
console.log(results.rows.item(0).name);
}
OUTPUT: undefined
I’ve tried using different numbers on the query and on the array but nothing works. I assume that the query is wrong.
Thanks!
Well, for a start do you have a row where the ID is 1?
Secondly, since you’re only selecting the
idcolumn in your second statement, why do you think you’re going to be able to accessname?Thirdly, it makes little sense to limit your query to the first row without an
order byclause. SQL is free to return the rows in any order it wants without that clause.If you really want the name for the first ID in the table, something like:
should do the trick. There are very few use cases where it makes sense to do
select *.If you want the fourth row, use something like:
See here for more details.