not getting the correct data - c#

in my log in form I set a username and password and after that I set a query on my Employee_Details then if it successfully log in it will write on another table for history reference so I set a username and Date of log in but it always get the username and password during write in my Employee_History table.Please help me.
private void signin_Click(object sender, EventArgs e)
{
if (IsValidated())
{
try
{
DataTable dt = new DataTable();
String Account_Type;
OleDbConnection con = new OleDbConnection();
con.ConnectionString = #"Provider = Microsoft.ACE.OLEDB.12.0; Data Source = C:\dbms\jollibee.accdb";
con.Open();
OleDbCommand cmd = new OleDbCommand();
cmd.Connection = con;
cmd.CommandText = "select * from Employee_Details where username = #username and password = #password and account_Type";
cmd.Parameters.AddWithValue("#username", username.Text);
cmd.Parameters.AddWithValue("#password", password.Text);
OleDbDataReader read = cmd.ExecuteReader();
dt.Load(read);
if(dt.Rows.Count > 0)
{
Account_Type = dt.Rows[0][3].ToString().Trim();
MessageBox.Show("Login Successfull.", "Success", MessageBoxButtons.OK, MessageBoxIcon.None);
if (Account_Type.Equals("Administrator"))
{
admin a = new admin();
a.Show();
this.Hide();
}
else if (Account_Type.Equals("Manager"))
{
supervisor s = new supervisor();
s.Show();
this.Hide();
}
else if (Account_Type.Equals("Cashier"))
{
cashier c = new cashier();
c.Show();
this.Hide();
}
} else
{
MessageBox.Show("Please check your username and password if correct. Please try again.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
cmd.CommandText = "insert into Employee_History (username, DateLogin) values (?,?);";
cmd.Parameters.AddWithValue("#username", username.Text);
cmd.Parameters.AddWithValue("#DateLogin", DateTime.Now.ToString("MM/dd/yyyy HH:mm"));
cmd.ExecuteNonQuery();
con.Close();
}
catch (Exception ex)
{
MessageBox.Show("Error" + ex.Message, "Error",MessageBoxButtons.OK, MessageBoxIcon.Error );
}
}
}

You are using positional arguments and not clearing the existing arguments. Simply setting a new command text does not "clear" the command, you have to clear it yourself:
cmd.Parameters.Clear(); //<---- ADD THIS LINE
cmd.CommandText = "insert into Employee_History (username, DateLogin) values (?,?);";
cmd.Parameters.AddWithValue("#username", username.Text);
cmd.Parameters.AddWithValue("#DateLogin", DateTime.Now.ToString("MM/dd/yyyy HH:mm"));
cmd.ExecuteNonQuery();
I do applaud you for using parameters in your query, I would encourage you to not store passwords in clear text as the next exercise.

Related

Login IF statement , the else always getting displayed, possible wrong written script

I always get the "else", even though I add the correct username and password
Photo with the script
private void button1_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(CONSTRing);
con.Open();
string q = "select * from LOGG where username = '" + tbu.Text + "' and password = '" + tbp.Text + "'";
SqlCommand cmd = new SqlCommand(q, con);
SqlDataAdapter Da = new SqlDataAdapter(cmd);
DataTable DT = new DataTable();
Da.Fill(DT);
if (DT.Rows.Count == 1)
{
Form Main = new Form();
MessageBox.Show("Welcome " + tbu.Text);
this.Hide();
Main.Show();
}
else
{
MessageBox.Show("Check your Username and Password");
}
con.Close();
}
Photo with dbo.LOGG
I will try to be helpful with an answer since I can't yet comment ;_;
Below is some code I compiled as an improvement to the one you posted.
private void button1_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(connectionString);
con.Open();
string q = "select 1 from LOGG where username = #username and password = #password";
SqlCommand cmd = new SqlCommand(q, con);
cmd.Parameters.AddWithValue("#username", tbu.Text); //
cmd.Parameters.AddWithValue("#password", tbp.Text); // using parameters to avoid intentional or accidental SqlInjection by the user
using (SqlDataReader reader = cmd.ExecuteReader())
{
try
{
con.Open();
if (reader.Read())
{
Form Main = new Form();
MessageBox.Show("Welcome " + tbu.Text);
this.Hide();
Main.Show();
}
else
{
MessageBox.Show("Check your Username and Password");
}
con.Close();
cmd.Dispose();
con.Dispose();
}
catch (Exception ex)
{
MessageBox.Show("Oops something went wrong. Error: " + ex.Message);
}
}
}
This is how I would write a quick version of what you wanted. Now, it might not help you out with your issue but it fixes some of the more obvious issues that might come up.
The Try and Catch block are there just for basic error handling to let the user know something went wrong.
The SqlDataReader is enough to notify you if a user with the given parameters exists in the database.
The check you used before
if (Dt.Rows.Count == 1)
{
//...
}
would fail to trigger if your query returned more than 1 row, which should not happen if the Table is created correctly. Check for duplicate entries in your table.

double data inserted in sql c#

This is just a simple way of registering new account credentials. My problem is that whenever I click the save button, the data will be saved twice in the database.
Sample image of the double entry in the database.
using (SqlConnection con = new SqlConnection(conString))
{
try
{
string query = ("INSERT INTO Tbl_Staff (Name,pos,username,password) VALUES (#name,#pos,#username,#password)");
using (SqlCommand cmd = new SqlCommand(query, con))
{
cmd.Parameters.AddWithValue("#name", textBox1.Text);
cmd.Parameters.AddWithValue("#pos", textBox4.Text);
cmd.Parameters.AddWithValue("#username", textBox2.Text);
cmd.Parameters.AddWithValue("#password", textBox3.Text);
con.Open();
cmd.ExecuteNonQuery();
int result = cmd.ExecuteNonQuery();
//MessageBox.Show(result.ToString());
// Check Error
if (result > 0)
MessageBox.Show("Credentials has been successfully added.","" ,MessageBoxButtons.OK, MessageBoxIcon.Information);
textBox1.Text = "";
textBox2.Text = "";
textBox3.Text = "";
textBox4.Text = "";
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
You're calling ExecuteNonQuery() twice.
cmd.ExecuteNonQuery();
int result = cmd.ExecuteNonQuery();
you excecute the query twice.
change:
con.Open();
cmd.ExecuteNonQuery();
int result = cmd.ExecuteNonQuery();
to
con.Open();
int result = cmd.ExecuteNonQuery();

C# update code for logout using mysql

im doing an update statement where the datetimepicker(logout) will insert into the same row as login but its making another row when i logout here is the link : http://imgur.com/a/rAWhi
ps. the problem here is the logout button is inserting into another row.. but i want to insert it in the same row.
here is my code :
private void button1_Click(object sender, EventArgs e)
{
con.Open();
MySqlCommand cmd = con.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "select * from empinfo where username = '" + label4.Text + "' and IDNUMBER = '" + textBox1.Text + "' ";
cmd.ExecuteNonQuery();
DataTable dt = new DataTable();
MySqlDataAdapter da = new MySqlDataAdapter(cmd);
da.Fill(dt);
i = Convert.ToInt32(dt.Rows.Count.ToString());
if (string.IsNullOrEmpty(textBox1.Text))
{
MessageBox.Show("Input your id number");
}
else if (i == 0)
{
MessageBox.Show("Username and IDNUMBER didn't match.", "Log-In Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
else
{
updateuser();
login frmm = new login();
frmm.Show();
this.Close();
}
con.Close();
}
public void updateuser()
{
MySqlConnection cnn = new MySqlConnection(mysqlAddress);
MySqlCommand cmdupdate;
cnn.Open();
try
{
cmdupdate = cnn.CreateCommand();
cmdupdate.CommandText = "update employee set logout = #logout";
cmdupdate.CommandText = "Insert into employee (logout) values (#logout)";
cmdupdate.Parameters.AddWithValue("#logout", dateTimePicker1.Value);
cmdupdate.ExecuteNonQuery();
}
catch (Exception)
{
throw;
}
finally
{
if (cnn.State == ConnectionState.Open)
{
cnn.Close();
MessageBox.Show("Data has been saved");
}
}
}
As #Ben in the comments pointed out, you do not need to use insert and only want update so change your code like this:
try
{
cmdupdate = cnn.CreateCommand();
cmdupdate.CommandText = "update employee set logout=#logout";
cmdupdate.CommandText += "WHERE IDNUMBER=#IDNUMBER";
cmdupdate.Parameters.AddWithValue("#IDNUMBER", textBox1.Text.Trim());
cmdupdate.Parameters.AddWithValue("#logout", dateTimePicker1.Value);
cmdupdate.ExecuteNonQuery();
}
The Where is to make sure it only updates the IDNUMBER on the textbox.
I think you should create different methods for login and logout like
For LOGIN
public static long id;
public void loginuser()
{
MySqlConnection cnn = new MySqlConnection(mysqlAddress);
MySqlCommand cmd;
cnn.Open();
try
{
cmd = cnn.CreateCommand();
cmd.CommandText = "Insert into employee (logout) values (#logout)";
cmd.Parameters.AddWithValue("#login", DateTime.Now);
cmd.ExecuteNonQuery();
id = cmd.LastInsertedId; // it will return the id of last inserted row
}
catch (Exception)
{
throw;
}
finally
{
if (cnn.State == ConnectionState.Open)
{
cnn.Close();
MessageBox.Show("Data has been saved");
}
}
}
For LOGOUT
public void logoutuser()
{
MySqlConnection cnn = new MySqlConnection(mysqlAddress);
MySqlCommand cmd;
cnn.Open();
try
{
cmd = cnn.CreateCommand();
cmd.CommandText = "update employee set logout = #logout WHERE IDNUMBER=#ID";
cmd.Parameters.AddWithValue("#logout", dateTimePicker1.Value);
cmd.Parameters.AddWithValue("#ID", id);
cmd.ExecuteNonQuery();
}
catch (Exception)
{
throw;
}
finally
{
if (cnn.State == ConnectionState.Open)
{
cnn.Close();
MessageBox.Show("Data has been saved");
}
}
}

Log MYSQL Login Details

I have a tool that logs into mysql but i'm trying to make it log when someone logs in or attempts to could anyone help me with this? It for some reason says can't connect to the mysql says cant find the connection if i add the log code below under the connection info
private void button1_Click(object sender, EventArgs e)
{
try
{
string MyConnection = "datasource=localhost;port=3306;username=root;password=password";
MySqlConnection MyConn = new MySqlConnection(MyConnection);
MySqlCommand MyCommand = new MySqlCommand("select * from bans.toollogin where user_name='" + this.UserTextBox.Text + "' and password='" + this.PassTextBox.Text + "' ;", MyConn);
MySqlDataReader MyReader;
string cmdText = "INSERT INTO logs(login, password) VALUES (login, password)";
MySqlCommand cmd = new MySqlCommand(cmdText, MyConn);
cmd.Parameters.AddWithValue("login", UserTextBox.Text);
cmd.Parameters.AddWithValue("password", PassTextBox.Text);
cmd.ExecuteNonQuery();
MyConn.Open();
MyReader = MyCommand.ExecuteReader();
int count = 0;
while (MyReader.Read())
{
Console.WriteLine(MyReader[count]);
count++;
}
if (count == 1)
{
MessageBox.Show("Username and password is correct");
this.Hide();
Form2 f2 = new Form2();
f2.ShowDialog();
}
else if (count > 1)
{
MessageBox.Show("Duplicate Username and passwor.\nAccess denied.");
}
else
{
MessageBox.Show("Username and password is incorrect.\nPleas try again.");
}
MyConn.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
The code i added to try make it log was
string cmdText = "INSERT INTO logs(login, password) VALUES (login, password)";
MySqlCommand cmd = new MySqlCommand(cmdText, MyConn);
cmd.Parameters.AddWithValue("login", UserTextBox.Text);
cmd.Parameters.AddWithValue("password", PassTextBox.Text);
cmd.ExecuteNonQuery();

Check if Username exists in Database

I am trying to code a register application form. In the code below I want to check if the username exists before i save the data in Database.
The problem here that the code doesn't go to the "else" statement.
Do I miss something? Kindly help
public void UserNameCheck()
{
string connetionString = null;
SqlConnection con;
connetionString = "Data Source=MCOEELIMENEM\\sqlexpress;Initial Catalog=Database;Integrated Security=True";
con = new SqlConnection(connetionString);
SqlCommand cmd = new SqlCommand("Select * from Register where Username= #Username", con);
cmd.Parameters.AddWithValue("#Username", this.textBox1.Text);
con.Open();
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
if (dr.HasRows == true)
{
MessageBox.Show("Username = " + dr[1].ToString() + " Already exist");
break;
}
else
{
cmd.CommandText = "insert into Register(Username,Password,Fullname,MobileNO,EmailID) values( #Username, #Password, #Fullname, #MobileNO, #EmailID)";
cmd.Parameters.AddWithValue("#Username", textBox1.Text);
cmd.Parameters.AddWithValue("#Password", textBox2.Text);
cmd.Parameters.AddWithValue("#Fullname", textBox3.Text);
cmd.Parameters.AddWithValue("#MobileNO", textBox4.Text);
cmd.Parameters.AddWithValue("#EmailID", textBox5.Text);
cmd.ExecuteNonQuery();
MessageBox.Show("Data Inserted Succesfully");
con.Close();
this.Hide();
Login lg = new Login();
lg.Show();
}
}
}
The query will not return any rows (therefore the Read() statement will fail) where the user exists.
Try this (untested):
SqlCommand cmd = new SqlCommand("Select count(*) from Register where Username= #Username", con);
cmd.Parameters.AddWithValue("#Username", this.textBox1.Text);
con.Open();
var result = cmd.ExecuteScalar();
if (result != null)
{
MessageBox.Show(string.format("Username {0} already exist", this.textBox1.Text));
}
else
{
...
If dr.Read() returns true, then your reader always has rows.
EDIT:
As long, as you do not getting any values from DB, you can remove while(dr.Read()) statement, and your code will work as you need
I recommand you to not select all columns, instead just select id and check with ExecuteScalar method of SqlCommand, that would be optimum solution.
SqlCommand cmd = new SqlCommand("Select id from Register where Username= #Username", con);
cmd.Parameters.AddWithValue("#Username", this.textBox1.Text);
con.Open();
var nId = cmd.ExecuteScalar();
if(nId != null)
{
// Prompt user is already exists
}
else
{
// Insert record
}
You must check with the number of rows returned by the query.

Categories

Resources