C# and MySql changing column var - c#

I'm making mysql register/login system in c#. I'm able to register and login with it.
I'm verify account with:
MySqlConnection conn = new MySqlConnection(db_creds);
try { conn.Open(); }
catch { throw new Exception("Can't access database"); }
MySqlDataAdapter adapter;
DataTable table = new DataTable();
string query = "SELECT `Nickname`, `Password` FROM `" + db_table + "` WHERE `Nickname` = '" + nickname + "' AND `Password` = '" + password + "'";
adapter = new MySqlDataAdapter(query, conn);
adapter.Fill(table);
conn.Close();
if(table.Rows.Count <= 0)
{
return false;
}
else { return true; }
After Nickname and Password I have varchar named active. My question is:
How can I change "active" (only for this user) to 1 when user succesfully logged in? and when logoff change it to 0?

To alter a single row in the table, you need to get it's ID(unique identifier for this table). Let the name for this unique column be str_Id, then retrieve this id for the particular user name and password. Then you can update the active state based on this unique identifier.
Another important advise for you is, don't use this type of plain-text queries, which will opens a wide door for SQL Injection. So i strongly recommend you to use parameterized queries as follows;
string query = "SELECT Nickname,str_Id FROM your_table_name" +
" WHERE Nickname =#nickname AND Password = #password";
MySqlConnection con = new MySqlConnection();
// Creating parameterized command
MySqlCommand cmd = new MySqlCommand(query, con);
cmd.Parameters.Add("#nickname", MySqlDbType.VarChar).Value = nickname;
cmd.Parameters.Add("#password", MySqlDbType.VarChar).Value = password;
MySqlDataAdapter adapter = new MySqlDataAdapter(cmd);
DataTable table = new DataTable();
// Collect the details to a DataTable
adapter.Fill(table);
if (table.Rows.Count>0) // Means there is some record found
{
// Get theUnique ID for the matching record
string uniqueId = table.Rows[0]["str_Id"].ToString();
// Update active state for that particular user
query = "Update your_table_name set active='0' Where str_Id=#str_Id";
cmd = new MySqlCommand(query, con);
cmd.Parameters.Add("#str_Id", MySqlDbType.VarChar).Value = uniqueId;
// Execute command here
}
else
{
// Print message thet no user found
}

When you verify if user exists and if password is correct and return message there you need to add update command for your database.
With that update command you need to update column ACTIVE to 1 but to that user, so you need to use this:
UPDATE table_name
SET column1=value1
WHERE some_column=some_value;
So in your case
UPDATE db_table SET active = 1 WHERE nickname = ' + nickname + '
So user now have status of ACTIVE.
Now you need to set it to inactive when he log off, so you do that when he press log off button or when he close the program, but with same principle
UPDATE db_table SET active = 0 WHERE nickname = ' + nickname + '

Related

Delete SQL row and change Id

I am making a C# tool that connects to a SQL database to manage users for another program I created. I'm displaying the Users in a ListBox, and I can add/delete users. Things got weird after I deleted some profiles, and I thought that could have something to do with how I delete the row from the database. I'm using an Id that automatically increases with every new user creation. This is my code for deleting from the database:
using (conn = new SqlConnection(connectionString))
using (SqlCommand command = new SqlCommand("DELETE FROM myDatabase WHERE Id = '" + (listBox1.SelectedIndex + 1) + "'", conn))
{
conn.Open();
command.ExecuteNonQuery();
}
and this is how I load the users into my listbox:
using (conn = new SqlConnection(connectionString))
using (SqlDataAdapter sqlAdapt = new SqlDataAdapter("SELECT * FROM myDatabase", conn))
{
DataTable dataTable = new DataTable();
sqlAdapt.Fill(dataTable);
listBox1.DisplayMember = "Name";
listBox1.ValueMember = "Id";
listBox1.DataSource = dataTable;
}
How can I delete the correct row from the database?
You should use the property SelectedValue to find your ID not the SelectedIndex
if(listBox1.SelectedValue != null)
{
int userID = Convert.ToInt32(listBox1.SelectedValue);
using (conn = new SqlConnection(connectionString))
using (SqlCommand command = new SqlCommand("DELETE FROM myDatabase WHERE Id = #uid", conn))
{
conn.Open();
command.Parameters.Add("#uid", MySqlDbType.Int32).Value = userID;
command.ExecuteNonQuery();
}
}
The problem with SelectedIndex is that this value goes from 0 to the max number of items in the listbox. This value has nothing to do with the ID of your user automatically calculated by your database. (After just one delete and one add these value are out of synch)
Note also that an sql text should never built using string concatenation. This is a well know security problem called Sql Injection.
"DELETE FROM myDatabase WHERE Id = '" + (listBox1.SelectedIndex + 1) + "'"
I'm not sure about mySQL, but it looks like you pass a string instead of an int.
When you pass a parameter as a number you should remove the " ' ".
so, it will look like:
"DELETE FROM myDatabase WHERE Id = " + (listBox1.SelectedValue)

Login form for website using web service in asp.net

I am trying to log in to a web service from a website. I have an access database with table USERS (id, user, pass, int admin(1 if it is, 0 if it isn't).
In the web service I have this webmethod:
[WebMethod]
public DataSet login(string u, string p)
{
OleDbConnection CNN = null;
OleDbCommand CMD = null;
string sql = "select * from users where username ='" + u + "' and pass='" + p + "' ";
CNN = new OleDbConnection(conn);
CMD = new OleDbCommand(sql, CNN);
CMD.Connection.Open();
OleDbDataAdapter adapter = new OleDbDataAdapter(CMD);
DataSet ds = new DataSet();
adapter.Fill(ds, "logged");
CNN.Close();
return ds;
}
And, in the web site I have this code:
protected void Button1_Click(object sender, EventArgs e)
{
db.Service Login = new db.Service();
Login.login(lUser.Text, lPass.Text);
}
So my question is how can I see if the logged user is admin or no ?
I was thinking somehow to read it from the DataSet ds - since it is filled with all the information that I need, but how to do that ?
Thanks,
dnisko
First of all please avoid passing user typed values to the database directly using sql strings. You are open to SQL Injection attacks and it is error prone as well
//Parametrize your following query.
string sql = "select * from users where username ='" + u + "' and pass='" + p + "' ";
Here is an example on how to parametrize OleDbCommand.
Answer to your question:
Your login() method returns a DataSet object, so you need to assign the return vale of login() method to a DataSet.
db.Service Login = new db.Service();
DataSet ds = Login.login(lUser.Text, lPass.Text);
bool isAdmin = false;
//Check if there is a record for the username and password
if(ds.Tables[0].Rows.Count == 1)
{
//now check if user is an admin or not
isAdmin = Convert.ToBoolean(ds.Tables[0].Rows[0]["admin"]);
if(isAdmin)
{
//User is an admin
}
}else{
//User does not exist in the database
}

ASP.NET Login, invalid password

con.Open();
string mysql; // generate an sql insert query for the database
mysql = "SELECT 1 FROM [Users] WHERE Username=? AND Password=?";
OleDbCommand cmd = new OleDbCommand(mysql, con);
cmd.Parameters.AddWithValue("#p1", tbUser.Text);
cmd.Parameters.AddWithValue("#p2", tbPass.Text);
cmd.ExecuteNonQuery();
int temp = Convert.ToInt32(cmd.ExecuteScalar().ToString());
if(temp==1)
{
Session["LogIn"] = lblUser.Text;
lblLogin.Text = "Welcome " + lblUser.Text + ", you are now logged in.";
}
else
{
lblLogin.Text = "Invalid Username/Password!";
}
con.Close();
Error: Syntax error in FROM clause.
"OleDbException was unhandled by user code."
Thanks.
EDIT
Now that I look closer there are many things wrong with this code. Standard practice is to check for the username/password combination in one shot:
mysql = "SELECT 1 FROM [User] WHERE UserName=? AND Password=?";
OleDbCommand CheckUser = new OleDbCommand(mysql, con);
// Add OleDbParameters here with the correct type/length
CheckUser.Parameters.Add("#userName", OleDbType.Char, 20).Value = tbUser.Text ;
CheckUser.Parameters.Add("#password", OleDbType.Char, 20).Value = tbPass.Text ;
int temp = Convert.ToInt32(CheckUser.ExecuteScalar().ToString());
and adding parameters to the command with the username and password values. That way hackers can't determine valid usernames without knowing the password.
This block:
mysql2 = "SELECT * FROM [User] WHERE Password='" + tbPass.Text + "'";
OleDbCommand Pass = new OleDbCommand(mysql2, con);
string Password = Pass.ExecuteScalar().ToString();
Will return the first column form the first row of the result set. Unless Password is the first column in the User table, you're not getting the password back, you're getting some other value.
It could be:
mysql2 = "SELECT password FROM [User] WHERE Password='" + tbPass.Text + "'";
OleDbCommand Pass = new OleDbCommand(mysql2, con);
string Password = Pass.ExecuteScalar().ToString();
First, just because it builds doesn't mean it's right.
Second, your code is vulnerable to SQL injection.
Third, without an error message or intent there's no way for us to divine what's wrong.
Last but not least: your code will only work if the first row of the first column obtained with the query returns a value of 1. I don't know what you're doing but if all else works for you, you may want to check that.
You can simply do it as :
con.Open();
string mysql; // generate an sql insert query for the database
mysql = "SELECT 1 FROM [Users] UserName='" + tbUser.Text + "' AND
Password='"+ tbPass.Text+"'";
OleDbCommand CheckUser = new OleDbCommand(mysql, con);
int temp = Convert.ToInt32(CheckUser.ExecuteScalar());
if(temp==1)
{
//Login
}
else
{
//Invalid UserName or Password.
}

Storing table column value into variable (SQL Server)

I have been stuck on this problem for some time: I am trying to save a value from a column in a table (database), under a certain condition.
In the code below I am trying to compare the input of a textbox (sUserName) with a value in a column (UserName) in the table (aspnet_Membership). If these values are equal, I want to fetch the specific Email value in a column and save it as a string variable.
If UserName (column) does not equal sUserName (textbox), then I would like to display an error message (else statement). The Email and UserName column are in the same table
string sUserName = txtBoxUsername.Text;
SqlConnection conn2 = new SqlConnection(#"Data Source=.\SQLEXPRESS;AttachDbFilename=C:\Users\sunny\Visual Studio 2010\Projects\email\Prac 2\App_Data\aspnet_Membership.mdf;Integrated Security=True;User Instance=True");
SqlCommand myCommand = new SqlCommand("SELECT Email FROM aspnet_Membership WHERE UserName = sUserName", conn2);
Just add checking if user exist on your table to your code something like:
string sUserName = txtBoxUsername.Text;
SqlConnection conn2 = new SqlConnection("Your SQL Connection");
SqlCommand myCommand = new SqlCommand("SELECT Email FROM aspnet_Membership WHERE UserName = '"+ sUserName + "'", conn2);
SqlDataReader rdr = myCommand.ExecuteReader();
if (dr.HasRows)
{
while (rdr.Read())
{
// User exist - get email
string email = rdr["Email "].toString();
}
}
else
{
//Error! user not exist
}
Best Regards

c# loop through Access DB

I have folowing code of c# in which I am making connection with access db and and using some conditions.I call a single row from db by using where clause in query.When I Logged into the page it gets data accurately.But after some time when i refresh the page it shows the folowing error
"There is No Row at position 0"
My code is is Bellow
protected void Page_Load(object sender, EventArgs e)
{
OleDbConnection con = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0; Data Source=|DataDirectory|OID.mdb;Persist Security Info=False;");
//OleDbConnection con = new OleDbConnection("Data Source=sml; User ID=sml; Password=sml; provider=OraOLEDB.Oracle");
OleDbCommand cmd = new OleDbCommand();
cmd.CommandText = "Select * from EMAILS WHERE EMAIL= '" + GlobalData.Email + "'";
//cmd.CommandText = "Select * from EMAILS";
cmd.CommandType = CommandType.Text;
cmd.Connection = con;
OleDbDataAdapter da = new OleDbDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
String email = ds.Tables[0].Rows[0][1].ToString();
if (email == GlobalData.Email)
{
Label2.Text = GlobalData.Email;
Label1.Text = GlobalData.Name;
Label3.Text = GlobalData.LastName;
Label1.Visible = false;
Label3.Visible = false;
Label4.Text = Label1.Text + ' ' + Label3.Text;
}
}
I am querying data from DB and using where cluse with Global Variable to retrive a single row
Can Any one Please tell me that how can i Remove this issue or can i loop through the DB that evry time when user login it gets data using loop and then follow the condtion
That means your query is not returning anything and therefore when you call this line:
String email = ds.Tables[0].Rows[0][1].ToString();
You get an exception because there's no Row[0]
If you want to avoid that error do something like:
if (ds.Tables[0].Rows.Count>0)
{
String email = ds.Tables[0].Rows[0][1].ToString();
///...
}
Don't do select * ever in your code. Get used to list the exact columns you want to select from the table. For example:
select email_address from Emails where id= 5
Extra comment: Your query above is kind of pointless; it seems that you are trying to select an email address from a table using the same email address in the where clause. Why do you need to select it from the database if you already know the email? Judging by the variable name (GlobalData.Email) it seems that this is a predefined value...

Categories