I've created a database using mysql, on my form1 there are two textboxes username and password and a login button. My program retrieves information from database and if the data s matches it logs in else an messagebox should pop up telling that username of password is wrong ( which it doesn't show)
before posting the code:
I've declared: the following
public int logid;
public int loginid(strign name) // to set logid the id of the user
public void loginfun(); // checks the data and logs in if id and password matches, else should give an error message.
and my code is as follows:
public int loginid(string name)
{
string conString = "Server=localhost;Database=ozturk;Uid=_____;pwd=_____";
MySqlConnection mcon = new MySqlConnection(conString);
string getid = "SELECT username,id from ozturk.admin WHERE username='" + name + "'";
MySqlCommand cmd = new MySqlCommand(getid, mcon);
MySqlDataReader myReader;
mcon.Open();
myReader = cmd.ExecuteReader();
while (myReader.Read())
{
if (myReader["username"].ToString() == name)
{
return Convert.ToInt32(myReader["id"].ToString());
}
}
return 0;
}
public void loginfun()
{
string conString ="Server=localhost;Database=ozturk;Uid=_____;pwd=_____";
MySqlConnection mcon = new MySqlConnection(conString);
string selectCommand = "SELECT * FROM ozturk.admin";
MySqlCommand cmd = new MySqlCommand(selectCommand,mcon);
MySqlDataReader myReader;
mcon.Open();
myReader = cmd.ExecuteReader();
while (myReader.Read())
{
try
{
if (myReader["username"].ToString() == txtuserid.Text && myReader["password"].ToString() == txtpassword.Text)
{
// set logid to userid
logid = loginid(myReader["username"].ToString());
string updateCommand = "UPDATE ozturk.admin SET status = 'on' WHERE id='" + logid + "' ";
MySqlConnection newcon = new MySqlConnection(conString);
MySqlCommand cmd2 = new MySqlCommand(updateCommand, newcon);
MySqlDataReader myReader2;
newcon.Open();
myReader2 = cmd2.ExecuteReader();
Anasayfa anasayf = new Anasayfa();
anasayf.Show();
this.Hide();
}
}
catch (Exception)
{
MessageBox.Show("Username or Password is incorrect");
throw;
}
}
}
The problem is: My program logs in and opens the other form if the username and the password is correct however it doesn't do anything if the username or password is wrong, What am I missing here? any help is appreciated
Thanks
I've solved the problem, here is what I've done: I've changed my login function from void to bool: here is the latest code:
public bool loginfun()
{
string conString ="Server=localhost;Database=ozturk;Uid=_____;pwd=_____";
MySqlConnection mcon = new MySqlConnection(conString);
string selectCommand = "SELECT * FROM ozturk.admin";
MySqlCommand cmd = new MySqlCommand(selectCommand,mcon);
MySqlDataReader myReader;
mcon.Open();
myReader = cmd.ExecuteReader();
while (myReader.Read())
{
try
{
if (myReader["username"].ToString() == txtuserid.Text && myReader["password"].ToString() == txtpassword.Text)
{
// giriş yapan kişinin id si
logid = loginid(myReader["username"].ToString());
string updateCommand = "UPDATE ozturk.admin SET status = 'on' WHERE id='" + logid + "' ";
MySqlConnection newcon = new MySqlConnection(conString);
MySqlCommand cmd2 = new MySqlCommand(updateCommand, newcon);
MySqlDataReader myReader2;
newcon.Open();
myReader2 = cmd2.ExecuteReader();
return true;
}
}
catch (Exception ee)
{
MessageBox.Show(ee.Message);
throw;
}
}
return false;
}
and inside the login button the code is as follows:
if (loginfun() == true)
{
Anasayfa anasayf = new Anasayfa();
anasayf.Show();
this.Hide();
}
else
{
MessageBox.Show("Username or Password is incorrect");
}
Thank you everyone for the tips
This is your code:
bool flag = false;
while (myReader.Read())
{
try
{
if (myReader["username"].ToString() == txtuserid.Text && myReader["password"].ToString() == txtpassword.Text)
{
// set the flag to true, is credentials match and break from the loop
flag = true;
break;
// set logid to userid
logid = loginid(myReader["username"].ToString());
string updateCommand = "UPDATE ozturk.admin SET status = 'on' WHERE id='" + logid + "' ";
MySqlConnection newcon = new MySqlConnection(conString);
MySqlCommand cmd2 = new MySqlCommand(updateCommand, newcon);
MySqlDataReader myReader2;
newcon.Open();
myReader2 = cmd2.ExecuteReader();
Anasayfa anasayf = new Anasayfa();
anasayf.Show();
this.Hide();
}
}
catch (Exception)
{
MessageBox.Show("Username or Password is incorrect");
throw;
}
}
if(!flag)
{
MessageBox.Show("Username or Password is incorrect");
}
Related
I can't find my problem. Can anyone help me to check it. I'm new in C#.
public void Btnchange_Click(object sender, EventArgs args)
MySqlConnection con = new MySqlConnection("server=localhost;user id=root;persistsecurityinfo=True;database=user;password=1234");
MySqlDataAdapter sda = new MySqlDataAdapter("select Password from user.register where Password='" + textoldpassword.Text + "'", con);
DataTable dt = new DataTable();
sda.Fill(dt);
if (dt.Rows.Count.ToString() == "1")
{
if (textnewpassword.Text == textconfirmpassword.Text)
{
con.Open();
MySqlCommand cmd = new MySqlCommand("update user.register set Password ='" + textconfirmpassword.Text + "' where Password ='" + textoldpassword.Text + "'", con);
cmd.ExecuteNonQuery();
con.Close();
lblmsg.Text = "Succesfully Updated";
lblmsg.ForeColor = Color.Green;
}
else
{
lblmsg.Text = "New password and confirm password should be same!";
}
I expect it can update and change my password.
There are many many (mostly) minor mistakes in your code:
use some kind of Id fields in your sql tables
never do an update like you did (update the field WHERE this field is equals to...)
create your own class and bind the query result to this class
when a class implements IDisposable interface, always use the keyword 'using'
never ever user string concatenation in sql queries!!! SQL INJECTION!!! always use parametrized sql queries
Here's a simple example for your form. Let's suppose your
user.register table has the following columns:
- Id
- Username
- Password
Now let's create your own class (maybe right under your button click
event, so it can be private this time):
private class MyUser
{
public int Id { get; set; }
public string Username { get; set; }
public string Password { get; set; }
}
Then your button click event should look like this:
private void Btnchange_Click(object sender, EventArgs e) {
if (!textnewpassword.Text.Trim().Equals(textconfirmpassword.Text.Trim()))
{
throw new ArgumentException("New password and confirm password should be same!");
}
List<MyUser> myUsers = new List<MyUser>();
using (MySqlConnection con =
new MySqlConnection(
"server=localhost;user id=root;persistsecurityinfo=True;database=user;password=1234"))
{
using (MySqlCommand cmd = new MySqlCommand("select * from user.register where Username=#user and Password=#pass", con))
{
cmd.Parameters.AddWithValue("#user", textusername.Text.Trim());
cmd.Parameters.AddWithValue("#pass", textoldpassword.Text.Trim());
if (cmd.Connection.State != ConnectionState.Open) cmd.Connection.Open();
using (MySqlDataReader dr = cmd.ExecuteReader())
{
while (dr.Read())
{
myUsers.Add(new MyUser
{
Id = (int)dr["Id"],
Username = dr["Username"].ToString(),
Password = dr["Password"].ToString()
});
}
}
if (cmd.Connection.State == ConnectionState.Open) cmd.Connection.Close();
}
if (!myUsers.Any())
{
throw new ArgumentException("No users found with the given username/password pair!");
}
if (myUsers.Count != 1)
{
throw new ArgumentException("More than 1 user has the same username and password in the database!");
}
MyUser user = myUsers.First();
user.Password = textnewpassword.Text.Trim();
using (MySqlCommand cmd = new MySqlCommand("update user.register set Password=#pass where Id=#id"))
{
cmd.Parameters.AddWithValue("#pass", user.Password);
cmd.Parameters.AddWithValue("#id", user.Id);
if (cmd.Connection.State != ConnectionState.Open) cmd.Connection.Open();
cmd.ExecuteNonQuery();
if (cmd.Connection.State == ConnectionState.Open) cmd.Connection.Close();
}
} }
...and so on.
I try something good code about prevent duplication of entries but I got error about connection. How can I fix this? Here's my code.
if(label1.Text == "" || label2.Text == "" || label3.Text == "") {
MessageBox.Show("Please Select Data");
} else {
String query = "Select * from Attendance where empIn=#empIn";
MySqlCommand cmd1 = new MySqlCommand(query, con);
cmd1.Parameters.AddWithValue("empIn", label2.Text);
MySqlDataReader dr = cmd1.ExecuteReader();
if (dr.HasRows) {
MessageBox.Show("This Person has already IN");
} else {
insert();
}
}
}
public void insert()
{
int i;
con.Open();
MySqlCommand cmd = new MySqlCommand("INSERT INTO Attendance (Name,Date,empIn)VALUES(#Name,#Date,#empIn)", con);
cmd.Parameters.Add("#Name", MySqlDbType.VarChar).Value = label3.Text;
cmd.Parameters.Add("#Date", MySqlDbType.Date).Value = Convert.ToDateTime(label1.Text);
cmd.Parameters.Add("#empIn", MySqlDbType.VarChar).Value = label3.Text;
i = cmd.ExecuteNonQuery();
if (i > 0) {
MessageBox.Show("Data Inserted");
label2.Text = "";
label3.Text = "";
label4.Text = "";
} else {
MessageBox.Show("Not Deleted");
}
con.Close();
you can simply use the "using" state which will create and close the connection automatically
public object getQueryScaller(string sqlQuery)
{
object value = null;
using (SqlConnection conn = new SqlConnection(_connectionString))
{
using (SqlCommand cmd = new SqlCommand(sqlQuery, conn))
{
conn.Open();
value = cmd.ExecuteScalar();
}
}
return value;
}
This will Automatically control the connection problem you will have no need to take care of it. just passing the parameter into the function as SQL statement and it will work.
When I enter user name and password, it logs in successfully and also opens desired field but when I enter wrong name or password (not saved in DB) it shows nothing actually it should encounter "else" this is the code
private void signin_button_Click(object sender, EventArgs e)
{
string connectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source= D:/Student_Managment_System/SMS1.mdb";
OleDbConnection myConnection = new OleDbConnection(connectionString);
myConnection.Open();
OleDbCommand cmd = new OleDbCommand();
cmd.Connection = myConnection;
string usrname = name_textBox.Text;
string passwd = pass_textBox.Text;
OleDbCommand cmd1 = new OleDbCommand("select * from Manager where Name='" + usrname + "' and Passwd='" + passwd + "'");
OleDbDataReader Reader = cmd1.ExecuteReader();
while (Reader.Read())
{
if (Reader[5].ToString() == "manager")
{
this.Hide();
Student_Info stuInf = new Student_Info();
stuInf.Show();
break;
}
else if (Reader[5].ToString() == "employee")
{
MessageBox.Show("log in as a employee ");
}
else
{
MessageBox.Show("Inviled User name or password");
}
}
myConnection.Close();
}
Your else statement isn't executed because there are no values to read when an invalid username or password is entered. You need to check if your reader has any rows. See here
Code
//Are there any rows
if(Reader.HasRows)
{
//If so read them
while (Reader.Read())
{
if (Reader[5].ToString() == "manager")
{
this.Hide();
Student_Info stuInf = new Student_Info();
stuInf.Show();
break;
}
else if (Reader[5].ToString() == "employee")
{
MessageBox.Show("log in as a employee ");
}
}
}
else
{
MessageBox.Show("Inviled User name or password");
}
private void admin_submit_button_Click(object sender, EventArgs e)
{
try
{
string myConnection = "datasource= localhost;port=3306;username=root;password=root";
MySqlConnection myConn = new MySqlConnection(myConnection);
MySqlCommand SelectCommand = new MySqlCommand("select * from mws.login_info where login_id='" + this.admin_id_textbox + "'and login_password1='" + this.admin_password_textbox1 + "' and login_password2='" + this.admin_password_textbox2 + "'");
MySqlDataReader myReader;
myConn.Open();
myReader = SelectCommand.ExecuteReader();
int count = 0;
while (myReader.Read())
{
count = count + 1;
}
if (count == 1)
{
MessageBox.Show("username and password is correct");
}
else
MessageBox.Show("username and password not correct");
myConn.Close();
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
}
You have not associated the command with the connection. You code lacks of the following line
SelectCommand.Connection = myConn ;
Said that, imagine that I write in your admin_id_textbox the following text
' OR login_id like '%' --
what happen to your checks for the correct login?
It is called Sql Injection and it is a very dangerous situation for every kind of database access.
Use always a parameterized query to build sql commands, in particular when part of your command is built using user input text
private void admin_submit_button_Click(object sender, EventArgs e)
{
try
{
string cmdText = #"select * from mws.login_info
where login_id=#id and login_password1=#pwd
and login_password2=#pwd2";
string myConnection = "datasource= localhost;port=3306;username=root;password=root";
using(MySqlConnection myConn = new MySqlConnection(myConnection))
using(MySqlCommand SelectCommand = new MySqlCommand(cmdText, myConnection))
{
myConn.Open();
SelectCommand.Parameters.AddWithValue("#id", this.admin_id_textbox);
SelectCommand.Parameters.AddWithValue("#pwd",this.admin_password_textbox1);
SelectCommand.Parameters.AddWithValue("#pwd2",this.admin_password_textbox2);
using(MySqlDataReader myReader = SelectCommand.ExecuteReader())
{
if(myReader.HasRows)
MessageBox.Show("username and password is correct");
else
MessageBox.Show("username and password not correct");
}
}
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
i am trying to make a windows form to log into another one,
i am using a database with users and passwords
the code is as follows:
private void button1_Click(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection("Data Source=mmtsql.XXX.XXXX.XX.XX;Initial Catalog=mmtXX-XXX;User ID=mmtXX-XXX;Password=mmtXX-XXX");
conn.Open();
SqlCommand mycommand = new SqlCommand("SELECT User, Password FROM UsersData WHERE User = '" + textBox1.Text + "' and Password = '" + textBox2.Text + "'", conn);
SqlDataReader reader = mycommand.ExecuteReader();
if(reader != null)
{
if(reader.Read())
{
Form1 formload = new Form1();
formload.Show();
}
else
{
label3.Text = "Invalid Username or Password !";
}
}
else
{
label3.Text = "Invalid Username or Password !";
}
the problem that a getting is that no matter what i insert into the textboxes, right or wrong i am getting:
Invalid Username or Password !
is there anyway to fix my code?
regards;
I would do it this way, keeping to the method you are using:
private void button1_Click(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection(conn_str);
conn.Open();
string sql = "SELECT User, Password
FROM UsersData WHERE User=#user and Password=#password"
SqlCommand mycommand = new SqlCommand(sql, conn);
//parameterize your query!
mycommand.Parameters.AddWithValue("user", txtuser.text);
mycommand.Parameters.AddWithValuye("password", txtpassword.password);
SqlDataReader reader = mycommand.ExecuteReader();
if(reader == null)
{
label3.Text = "Database query failed!";
}
else if(reader.HasRows)
{
Form1 formload = new Form1();
formload.Show();
}
else
{
label3.Text = "Invalid Username or Password !";
}
Use parameterized queries as they will help you against sql injection as mentioned by SLaks.
Change your code to below
using (SqlCommand command = new SqlCommand("SELECT User, Password
FROM UsersData WHERE User=#user and Password=#password", connection))
{
//
// Add new SqlParameter to the command.
//
command.Parameters.Add(new SqlParameter("user ", textbox1.text));
command.Parameters.Add(new SqlParameter("password", textbox2.text));
SqlDataReader reader = command.ExecuteReader();
if (reader == null)
{
Form1 formload = new Form1();
formload.Show();
}
else
{
label3.Text = "Invalid Username or Password !";
}
}