But it does not get the data from the database. I'm do not want to retrieve the data to the table and want to display data in particular line edit. What is the error? Is there any modification?
This is the Code that I'm using:
void Userdetails::on_pushButton_4_clicked()
{
delete ui;
// database connection
database = QSqlDatabase::addDatabase("QMYSQL");
database.setHostName("localhost");
database.setUserName("root");
database.setPassword("");
database.setDatabaseName("electricity");
if(database.open()) {
QSqlQuery qry;
QSqlQuery query(QSqlDatabase::database("MyConnect"));
query.prepare(QString("SELECT accno, fullname, address, telephone FROM user_reg_elec WHERE username = :username AND password = :password"));
if(query.exec()) {
query.exec();
while(query.next()) {
ui ->dislayaccountnumber ->setText(query.value(0).toString());
ui ->displayname ->setText(query.value(3).toString());
ui ->displayaddress ->setText(query.value(4).toString());
ui ->displattelephoneno ->setText(query.value(5).toString());
// ui ->displayamountoebill ->setText(query.value(6).toString());
}
} else {
QMessageBox::information(this, "Query did not execute", "Not successful executing the query");
}
} else {
QMessageBox::information(this, "Database not open", "Not opened successfully");
}
database.close();
}
This code has four main issues:
You have deleted the ui at the beginning of your code. Hence, the first line that calls ui-> will crash the program.
You have defined your query improperly. Also, your way to select a name for your connection is not right.
You have executed your query twice (one is enough).
You've not bind values for username and password.
Please use the following:
void Userdetails::on_pushButton_4_clicked() {
{
// database connection
QSqlDatabase database;
database = QSqlDatabase::addDatabase("QMYSQL","MyConnect");
database.setHostName("localhost");
database.setUserName("root");
database.setPassword("");
database.setDatabaseName("electricity");
if(database.open()) {
QSqlQuery query(database);
if (query.prepare(QString("SELECT accno, fullname, address, telephone FROM user_reg_elec WHERE username = :username AND password = :password"))) {
//Add bindings
query.bindValue(":username","your user name");
query.bindValue(":password","your password");
if(query.exec()) {
while(query.next()) {
ui ->dislayaccountnumber ->setText(query.value(0).toString());
ui ->displayname ->setText(query.value(1).toString());
ui ->displayaddress ->setText(query.value(2).toString());
ui ->displattelephoneno ->setText(query.value(3).toString());
// ui ->displayamountoebill ->setText(query.value(4).toString());
}
} else {
qDebug() << "Query did not execute due to: " << query.lastError().text();
QMessageBox::information(this, "Query did not execute", "Not successful executing the query");
}
} else {
qDebug() << "Query not prepared due to the following error: " << query.lastError().text();
}
} else {
qDebug() << "Database not opened due to: " << database.lastError().text();
QMessageBox::information(this, "Database not open", "Not opened successfully");
}
database.close();
}
QSqlDatabase::removeDatabase("MyConnect");
}
Please add #include <QSqlError> to the top, if you have not already included this library.
Only to the questionary:
To show details in a new window, after you got the target user's information from your database, you can create a new dialog (window) and show the results in it as follows:
//Create a new dialog
QDialog *dialog = new QDialog;
//Add some elements to the dialog
QLabel *accountNumber = new QLabel("Account number: " + query.value(0).toString());
QLabel *name = new QLabel("Name: " + query.value(1).toString());
QLabel *address = new QLabel("Address: " + query.value(2).toString());
QLabel *phoneNumber = new QLabel("Phone number: " + query.value(3).toString());
QVBoxLayout *lay = new QVBoxLayout;
lay->addWidget(accountNumber);
lay->addWidget(name);
lay->addWidget(address);
lay->addWidget(phoneNumber);
dialog->setLayout(lay);
//Show the dialog
dialog->open();
Related
I'm try to re-travel MYSQL database value to the QLine edit. I want to re-travel data according to the username and password. Username and password are in mainwindow.cpp. After login successfully, it's open second window named userdetails.cpp. I want to display data in this userdetails.cpp. This is the code I used in this moment.
void Userdetails::on_pushButton_4_clicked()
{
{
// database connection
QSqlDatabase database;
database = QSqlDatabase::addDatabase("QMYSQL","MyConnect");
database.setHostName("localhost");
database.setUserName("root");
database.setPassword("");
database.setDatabaseName("electricity");
if(database.open()) {
QSqlQuery query(database);
if (query.prepare(QString("SELECT accno, fullname, address, telephone FROM user_reg_elec WHERE username = :username AND password = :password"))) {
//Add bindings
query.bindValue(":username","username");
query.bindValue(":password","password");
if(query.exec()) {
while(query.next()) {
ui ->dislayaccountnumber ->setText(query.value(0).toString());
ui ->displayname ->setText(query.value(1).toString());
ui ->displayaddress ->setText(query.value(2).toString());
ui ->displattelephoneno ->setText(query.value(3).toString());
// ui ->displayamountoebill ->setText(query.value(4).toString());
}
} else {
qDebug() << "Query did not execute due to: " << query.lastError().text();
QMessageBox::information(this, "Query did not execute", "Not successful executing the query");
}
} else {
qDebug() << "Query not prepared due to the following error: " << query.lastError().text();
}
} else {
qDebug() << "Database not opened due to: " << database.lastError().text();
QMessageBox::information(this, "Database not open", "Not opened successfully");
}
database.close();
}
QSqlDatabase::removeDatabase("MyConnect");
}
When your application accepts a user (using a login phase), you should save the user id in your application and pass it using a set function member or even as parameter in your ctor of UserDetails. So, when your application displays the user details, you can create a SQL query referring directly the user throw her/him id, avoiding use any other field in where clausule.
A suggestion:
class Userdetails
{
private:
std::string _user;
...
setUser(const std::string & user){
_user = user;
}
...
}
But, I strongly recommend, for security reasons, the password should not be used, you already log in your user, and the user id IS unique.
I am making registration/login form with qt c++ saving registration information in mysql password is hashed by md5 also I've tried sha256 same there, so main problem it saves password hashed and I've got no problem with that but when i'm comparing it in login window it doesn't compares and password wrong message appears. without hashing everything works fine, with hashing checking problem. Thanks for help))
if (db.open()) {
QString email = ui->email->text();
QString password = QString("%1").arg(QString(QCryptographicHash::hash(ui->password->text().toUtf8(),QCryptographicHash::Md5).toHex()));
// Insert Query
QSqlQuery query(QSqlDatabase::database("MyConnection"));
query.prepare("SELECT * FROM users WHERE email = :email AND password = :password");
query.bindValue(":email", email);
query.bindValue(":password", password);
if (!query.exec()) {
QMessageBox::information(this,"Failed","Error please try again");
}
else {
QString emailLog = query.value(1).toString();
QString passwordLog = query.value(4).toString();
if (query.next()) {
QMessageBox::information(this,"SUCCESS","SUCCESS");
ui->plstryagain->close();
db.close();
} else {
QMessageBox::information(this,"Wrong","Wrong Password try again");
ui->plstryagain->show();
db.close();
}
}
}
else {
QMessageBox::information(this, "Database Error", "Can't Connect To Database");
}
I want to make a login system, I have mysql database I want to login according to my mysql database username and password but it is not working I think I have problem with my code please check the code
void MainWindow::on_loginBtn_clicked()
{
QSqlDatabase db;
db = QSqlDatabase::addDatabase("QMYSQL", "MyConnect");
db.setHostName("localhost");
db.setUserName("root");
db.setPassword("");
db.setDatabaseName("qtregister");
QString username = ui->loginEdit->text();
QString password = ui->loginPassword->text();
if(db.open()) {
QSqlQuery query(QSqlDatabase::database("MyConnect"));
query.prepare(QString("SELECT username and password from users where username = :username AND password = :password"));
query.bindValue(":username", username);
query.bindValue(":password", password);
if(!query.exec()) {
QMessageBox::information(this, "Failed", "Failed To Login");
}else {
QMessageBox::information(this, "Success", "Login Success");
}
}
else {
QMessageBox::information(this, "Not Connected", "Not Conneced Success");
}
}
UPDATED
There was an error in your query (Sometimes you need to debug your query in another environment that Qt like mysql clis or online ones http://sqlfiddle.com)
SELECT username,password from users where username = :username AND password = :password
instead of
SELECT username and password from users where username = :username AND password = :password
Corrected Answer
void MainWindow::on_loginBtn_clicked() {
QSqlDatabase db;
db = QSqlDatabase::addDatabase("QMYSQL", "MyConnect");
db.setHostName("localhost");
db.setUserName("root");
db.setPassword("");
db.setDatabaseName("qtregister");
QString username = ui - > loginEdit - > text();
QString password = ui - > loginPassword - > text();
if (db.open()) {
QSqlQuery query(db);
query.prepare(QString("SELECT username , password from users where username = :username AND password = :password"));
query.bindValue(":username", username);
query.bindValue(":password", password);
if (!query.exec()) {
QMessageBox::information(this, "Failed", "Error in executing query");
} else {
while (query.next()) {
QString usernameFromDB = query.value(0).toString();
QString passwordFromDB = query.value(1).toString();
qDebug() << usernameFromDB << passwordFromDB;
if (usernameFromDB == username && passwordFromDB == password)
QMessageBox::information(this, "Success", "Login Success");
else
QMessageBox::information(this, "Failed", "Username or password error");
}
}
} else {
QMessageBox::information(this, "Not Connected", "Not Conneced Success");
}
}
I am running into an issue with signing up a user into Parse-Server while using Facebook.
When the user clicks on the Sign up with facebook icon this code will run..
ParseFacebookUtils.logInWithReadPermissionsInBackground(LoginRegister.this, permissions, new LogInCallback() {
#Override
public void done(ParseUser user, ParseException err) {
if (user == null) {
MethodContants.showLog(TAG, "Uh oh. The user cancelled the Facebook login.", true);
} else if (user.isNew()) {
MethodContants.showLog(TAG, "User logged in through Facebook", false);
getUserDetailsFromFacebook();
} else {
MethodContants.showLog(TAG, "User logged in through Facebook", false);
Intent intent = new Intent(LoginRegister.this, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
startActivity(intent);
}
}
});
My getUserDetailsFromFacebook() method looks like this
private void getUserDetailsFromFacebook() {
GraphRequest graphRequest = GraphRequest.newMeRequest(AccessToken.getCurrentAccessToken(), new GraphRequest.GraphJSONObjectCallback() {
#Override
public void onCompleted(JSONObject jsonObject, GraphResponse response) {
try {
facebookUser = jsonObject.getString("name");
MethodContants.showLog(TAG, "json name object: " + jsonObject.getString("name"), false);
} catch (JSONException e) {
MethodContants.showLog(TAG, "Error when getting facebook name: " + e.getMessage(), true);
showToast("Error saving Facebook user.");
}
try {
facebookEmail = jsonObject.getString("email");
MethodContants.showLog(TAG, "json email object: " + jsonObject.getString("email"), false);
} catch (JSONException e) {
MethodContants.showLog(TAG, "Error when getting facebook email: " + e.getMessage(), true);
showToast("Error saving Facebook email.");
}
saveNewFacebookUser();
}
});
Bundle parameters = new Bundle();
parameters.putString("fields", "name,email");
graphRequest.setParameters(parameters);
graphRequest.executeAsync();
}
my saveNewFacebookUser() looks like this...
private void saveNewFacebookUser() {
final ParseUser newFacebookUser = new ParseUser();
Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.profile_picture);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte[] image = stream.toByteArray();
ParseFile file = new ParseFile(AppConstants.PARSEUSER_IMAGE_FILE_NAME, image);
newFacebookUser.setUsername(facebookUser);
newFacebookUser.setEmail(facebookEmail);
newFacebookUser.put(AppConstants.PARSEUSER_FULLNAME, facebookUser);
newFacebookUser.put(AppConstants.PARSEUSER_FIRST_TIME_LOGGED_IN, "true");
newFacebookUser.put(AppConstants.PARSEUSER_PROFILE_IMAGE, file);
file.saveInBackground(new SaveCallback() {
#Override
public void done(ParseException e) {
if (e == null) {
newFacebookUser.saveInBackground(new SaveCallback() {
#Override
public void done(ParseException e) {
if (e == null) {
// USER CREATED!
// TODO SEND AN EMAIL TO THE USER WITH USERNAME AND PASSWORD
Intent intent = new Intent(LoginRegister.this, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
startActivity(intent);
} else {
MethodContants.showLog(TAG, "Facebook Error:" + e.getMessage(), true);
showToast("Facebook Error: " + e.getMessage());
}
}
});
} else {
MethodContants.showLog(TAG, "Facebook Error:" + e.getMessage(), true);
showToast("Facebook Error: " + e.getMessage());
}
}
});
}
The error is telling me that I have to use signUpInBackground and not saveInBackground. However, when I do that, I get another error that says I need to save a password for the user -> which defeats the whole purpose of the facebook login.
Any help would be much appreciated!
I found the issue.
in the saveNewFacebookUser() method, I was setting it as a brand new user.
ParseUser new = new ParseUser();
This should have been
ParseUser new = ParseUser.getCurrentUser();
I will leave this up in case anyone has issues.
I'm trying to run this Qt code
QString serverName = "localhost";
QString dbName = "zfserver";
QString userName = "root";
QString passWord = "123456";
QSqlDatabase db = QSqlDatabase::addDatabase("QMYSQL");
db.setConnectOptions();
db.setHostName(serverName);
db.setDatabaseName(dbName);
db.setUserName(userName);
db.setPassword(passWord);
if(db.open())
{
QSqlQuery query;
query.prepare("INSERT INTO account (name, email, password, type) "
"VALUES (:name, :email, :password, :type)");
query.bindValue(":name", "atef");
query.bindValue(":email", "asfasf#gfasga.com");
query.bindValue(":password", "123");
query.bindValue(":type", "2");
if (query.exec())
{
qDebug() << "OK";
} else {
qDebug() << "Error" << query.lastError().text();
}
db.close();
}
But I'm getting this error
Error "Using unsupported buffer type: 1701601889 (parameter: 1) QMYSQL3: Unable
to bind value"
If I change the query without the bindValue it works. Is there a way to solve this?
Try to rebuild the SQL driver .
QMYSQL3 seems to be old.