I have a PyQt4 application that offers signup and sign in. The signup works well that is, the credentials are store in the database as intended. The problem is with sign-in where by it accepts any credentials including those that don't exist in the database.Below is the code am using.
self.database1 = QtSql.QSqlDatabase().addDatabase('QMYSQL')
self.database1.setHostName('localhost')
self.database1.setDatabaseName('database')
self.database1.setUserName('root')
self.database1.setPassword('')
if self.database1.open():
print('Successful')
else:
print(self.database1.lastError().text())
username = self.userName1.text()
password = self.passwordSlot.text()
query = QtSql.QSqlQuery(self.database1)
credentials = query.prepare("SELECT * FROM credentials WHERE username = ? and password = ?")
if credentials:
query.addBindValue(username)
query.addBindValue(password)
query.exec_()
self.database1.close()
print('Successfully logged in')
else:
print('Failed')
prepare()
returns a boolean value that indicates whether the statement is correct or not, so it can not indicate if the credentials match, since the correct statement will always be true, what you should know if the information is in the database is that the order returns at least one element, and we can do that with first()
:
self.database1 = QtSql.QSqlDatabase().addDatabase('QMYSQL')
self.database1.setHostName('localhost')
self.database1.setDatabaseName('database')
self.database1.setUserName('root')
self.database1.setPassword('')
if self.database1.open():
print('Successful')
else:
print(self.database1.lastError().text())
username = self.userName1.text()
password = self.passwordSlot.text()
query = QtSql.QSqlQuery(self.database1)
is_valid_query = query.prepare("SELECT * FROM credentials WHERE username = ? and password = ?")
if is_valid_query:
query.addBindValue(username)
query.addBindValue(password)
if query.exec_():
if query.first():
print('Successfully logged in')
else:
print('Failed')
else:
print(query.lastError().text())
self.database1.close()