0

I have the following code to create a database table if it does not already exist then check if the current user is in the database or not. I do this by selecting the user with id equal to their device id. The code right now should print hello world and then go to forms. However when I run the code nothing happens, no errors and no print statement. Any ideas why this might be happening?

local tablesetup = [[CREATE TABLE IF NOT EXISTS User (id VARCHAR(255) PRIMARY KEY, name);]]
    db:exec(tablesetup)

    --Check if the user is in the database already
    for row in db:nrows("SELECT * FROM User WHERE id = " .. "'" .. system.getInfo("deviceID") .. "'") do
        print("hello")
        if(row.id == nil) then
            print("world")
            storyboard.gotoScene("forms")
        end
    end

1 Answer 1

3

nrows returns all of the rows produced by a query. If no rows were produced in a query (because, for example, the item(s) you were looking for was not found), then the loop will not start. Because there was no row that matched the query.

If you're looking to detect if a query succeeded or not, then you'll need to actually check that.

Also, please stop building queries with string concatenation. Learn how to use prepared statements with proper value binding. It's much cleaner and has the benefit of not leaving you open to SQL injection attacks.

Sign up to request clarification or add additional context in comments.

3 Comments

well what I am trying to do is check if the user is in the database or not. So if they are not in the database the loop will just be skipped?
@ewein: Yes. Just like if you loop over an empty list, you don't go into the loop.
How do you "actually check that"? lua.sqlite.org/index.cgi/doc/tip/doc/lsqlite3.wiki there is no method which obviously tells you whether the result set is empty.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.