I'm hitting some trouble writing this in python and I can't seems to solve this other than using string formatting (Which is strongly not recommended)
Basically I call the function input() and ask for the user to type in some keyword (space separated) and I need to find all the posts with title containing any of the keywords.
For example, if the user input was "python SQL mysql", I need to find all the post that matches at least one of the keywords. In this example, the query will be
SELECT posts.title FROM posts
WHERE lower(posts.title) LIKE "%python%" OR
lower(posts.title) LIKE "%sql%" OR
lower(posts.title) LIKE "%mysql%";
However, here is the problem. The number of keywords could vary. Therefore I cannot write a fixed SQL statement like
db.execute("SELECT posts.title FROM posts WHERE posts.title LIKE ? OR posts.title LIKE ?",("%"+keyword1+"%", "%"+keyword2+"%"))
Instead I have to resort to a for loop in Python, something like:
query = "posts.title LIKE '%" + keywords[0] + "%'"
keywords.remove(0)
for k in keywords:
query += "OR posts.title LIKE '%" + k +"'%"
However this is obviously not recommended. While what I'm working on is a school project so it's not mission critical, plus we are not graded against SQL injection attacks, I do want to know what is the proper way to solve this question.