I have this code for managing logins, here is a small bit of it:
void Login::on_pushButton_clicked(){
QString user, password;
user = ui->username->text();
password = ui->pass->text();
QSqlQuery qry;
qry.prepare("SELECT id, name from users WHERE username = :username AND password = :password");
qry.bindValue(":username", user);
qry.bindValue(":password", password);{
int counter = 0;
while (qry.next()){
counter++;
}
if(counter==1)
ui -> statuslabel -> setText("Sign in successful");
if(counter<1)
ui -> statuslabel -> setText("Sign in unsuccessful");
}
}
On giving it the correct input (ie correct password and username) it does not work and proceed to the second if condition saying that Sign in is unsuccessful. I have a counter int type that counts how many instances of user input match the database tables. It is initialized to a zero which means that is not the problem. any ideas on what might be the case here?
You forgot to call
qry.exec()before accessing first element usingqry.next(). It should be called after lastqry.bindValue().Below is example how it can be done in your code:
Note: You don't have to use
QSqlQuery::nextto check if yourSELECTstatement return any result.QSqlQuery::sizemethod will return number of selected rows.