MySQL Syntax Error ASP.NET - c#

Good day!
I'm trying to figure out what error I'm having. This is the error:
And here is my code:
protected void accountGridView_RowEditing(object sender, GridViewEditEventArgs e)
{
accountGridView.EditIndex = e.NewEditIndex;
BindData();
}
protected void accountGridView_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
int user_id = int.Parse(accountGridView.DataKeys[e.RowIndex].Value.ToString());
TextBox txtUsername = (TextBox)accountGridView.Rows[e.RowIndex].FindControl("txtUsername");
UpdateUser(user_id, txtUsername.Text);
accountGridView.EditIndex = -1;
BindData();
}
private void UpdateUser(int user_id, string username)
{
GlobalVars cn = new GlobalVars();
MySqlConnection connection = cn.connectDB();
connection.Open();
string query = "UPDATE user SET username = '" + username + " WHERE user_id = " + user_id + "";
MySqlCommand com = new MySqlCommand(query, connection);
com.ExecuteNonQuery();
connection.Close();
}
I can't get it to work. Am I missing something here?
Any help would be much appreciated.

The error message says that you have syntax errors in your query, so the other parts(connection) are working well as expected. Now consider the query:- if you debug the program and watch the query you can see that it may look like:
UPDATE user SET username = 'asd WHERE user_id= usr_123
So what is wrong here is, You ware missed a ' after asd, need to give a pair of ' to specify the user_id(if it is a string), so the query may look like this:
string query = "UPDATE user SET username = '" + username + "' WHERE user_id = '" + user_id + "'";
But i strongly recommend you to use Parameterized queries instead for this to avoid injection. The parameterised query will looks like :
string query = "UPDATE user SET username = #username WHERE user_id = #user_id";
MySqlCommand com = new MySqlCommand(query, connection);
com.Parameters.Add("#username", MySqlDbType.VarChar).Value = username;
com.Parameters.Add("#user_id", MySqlDbType.VarChar).Value = user_id;
// execute query here

Related

How can I display multiple sessions in a web site in a list view?

When a user logs into the web site I am developing it the gets the session of the user by using this code:
protected void ButtonLogin_Click(object sender, EventArgs e)
{
Session["LoggedIn"] = UsernameTXT.Text;
....
Then I have a "Card" where it shows the total amount of "Online Users" which is set up in my Global.asax file:
void Application_Start(object sender, EventArgs e)
{
Application["OnlineUsers"] = 0;
}
void Session_Start(object sender, EventArgs e)
{
Application.Lock();
Application["OnlineUsers"] = (int)Application["OnlineUsers"] + 1;
Application.UnLock();
Session.Timeout = 8;
}
void Session_End(object sender, EventArgs e)
{
Application.Lock();
Application["OnlineUsers"] = (int)Application["OnlineUsers"] - 1;
Application.UnLock();
}
So to display the user that is logged in I have the following in my OnlineUsers.aspx.cs file:
protected void Page_Load(object sender, EventArgs e)
{
try
{
SqlConnection con = new SqlConnection(#"My Connection String");
con.Open();
SqlCommand cmd = new SqlCommand("SELECT first_name, last_name, email, user_name FROM tbl_um_user WHERE user_name = '"+ Session["username"].ToString() + "'", con);
cmd.CommandType = CommandType.Text;
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds, "ss");
GridViewOnline.DataSource = ds.Tables["ss"];
GridViewOnline.DataBind();
}
.......
This works perfectly, but when another users logs in it then doesn't display that users information as per above.
I have had a look on various other post here on Stack Overflow and some suggest that you need to save the session in a database and retrieve from there? I might be wrong but does it not create a new session every time a user logs in? So then surely I should be able to display it? And how do I save the sessions in a database? (Sorry for all the questions :-) )
Any guidance, explanation or help will be greatly appreciated.
Thank you
SAVING TO DATABASE
Session["LoggedIn"] = UsernameTxt.Text;
string connectionString = System.Configuration.ConfigurationManager
.ConnectionStrings["CONN"].ConnectionString;
using (SqlConnection connection = new SqlConnection(connectionString))
using (SqlCommand command = connection.CreateCommand())
{
command.CommandText = "UPDATE tbl_um_user SET IsLogged = #isLogged WHERE user_id_pk ='" + Session["LoggedIn"] + "'";
command.Parameters.AddWithValue("#isLogged", 1);
connection.Open();
command.ExecuteNonQuery();
connection.Close();
}
SESSION END
<%# Application Language="C#" %>
<script runat="server">
void Application_Start(object sender, EventArgs e)
{
Application["OnlineUsers"] = 0;
}
void Session_Start(object sender, EventArgs e)
{
Application.Lock();
Application["OnlineUsers"] = (int)Application["OnlineUsers"] + 1;
Application.UnLock();
Session.Timeout = 8;
}
void Session_End(object sender, EventArgs e)
{
Application.Lock();
Application["OnlineUsers"] = (int)Application["OnlineUsers"] - 1;
Application.UnLock();
string connectionString = System.Configuration.ConfigurationManager
.ConnectionStrings["CONN"].ConnectionString;
using (System.Data.SqlClient.SqlConnection connection = new System.Data.SqlClient.SqlConnection(connectionString))
using (System.Data.SqlClient.SqlCommand command = connection.CreateCommand())
{
command.CommandText = "UPDATE tbl_um_user SET IsLogged = 0 WHERE user_id_pk ='" + Session["LoggedIn"] + "'";
command.Parameters.AddWithValue("#isLogged", 0);
connection.Open();
command.ExecuteNonQuery();
connection.Close();
}
}
SqlCommand cmd = new SqlCommand("
SELECT first_name
, last_name
, email
, user_name
FROM tbl_um_user
WHERE user_name = '"+ Session["username"].ToString() + "'", con);
So the problem is in the last line:
WHERE user_name = '"+ Session["user","name"].ToString() + "'"
This will simply get the username of the user who is viewing the page (aka the session user).
If you want to resolve this you have to either store in memory the username of the users that log in everytime. You can use object cache. The logic is that when a user logs in you store his name in memory and then query with all those names.
WHERE user_name IN ("+ string.join(",", Your_Memory.Usernames)+ ")"
It's a simple list that stores the usernames.
Another solution would be for you to store them in your database with a simple flag you must create a column IsLogged BIT where you update it with 1 when the user logs in and when the user logs out make it a 0.
So you would query like this
WHERE IsLogged = 1
This eliminates the need for using in memory storing.
EDIT:
Session["LoggedIn"] = UsernameTxt.Text;
The error is because you try to compare your primary key which is an int with a string.
command.CommandText = "UPDATE tbl_um_user SET IsLogged = #isLogged WHERE user_id_pk ='" + Session["UserId"] + "'";
Here you have to get the userid. If you dont have the user id then search by username(if it is unique of course)
To update when session ends:
void Session_End(object sender, EventArgs e)
{
// your code
command.CommandText = "UPDATE tbl_um_user SET IsLogged = 0 WHERE user_id_pk ='" + Session["UserId"] + "'";
}
Just query the database on session_end just like you did on log in.

Updating records in SQL Server database using ASP.NET

I am new to ASP.NET, I am facing some difficulty in updating records inside database in ASP.NET. My code is showing no errors, but still the records are not being updated. I am using SQL Server 2012.
Code behind is as follows:
protected void Page_Load(object sender, EventArgs e)
{
if (Session["user"] != null)
{
con.Open();
string query = "Select * from Customers where UserName ='" + Session["user"] + "'";
SqlCommand cmd = new SqlCommand(query, con);
SqlDataReader reader = cmd.ExecuteReader();
if (reader.Read())
{
txt_name.Text = reader["CustName"].ToString();
txt_phonenumber.Text = reader["Contact"].ToString();
txt_address.Text = reader["CustAddress"].ToString();
txt_cardnum.Text = reader["CustAccountNo"].ToString();
txt_city.Text = reader["CustCity"].ToString();
txt_emailaddress.Text = reader["Email"].ToString();
txt_postalcode.Text = reader["CustPOBox"].ToString();
Cnic.Text = reader["CustCNIC"].ToString();
}
con.Close();
}
else
{
Response.Redirect("Login.aspx");
}
}
protected void BtnSubmit_Click(object sender, EventArgs e)
{
con.Open();
SqlCommand cmd2 = con.CreateCommand();
SqlCommand cmd1 = con.CreateCommand();
cmd1.CommandType = CommandType.Text;
cmd1.CommandText = "Select CustID from Customers where UserName = '" + Session["user"] + "'";
int id = Convert.ToInt32(cmd1.ExecuteScalar());
cmd2.CommandType = CommandType.Text;
cmd2.CommandText = "update Customers set CustName='" + txt_name.Text + "',CustCNIC='" + Cnic.Text + "',Email='" + txt_emailaddress.Text + "',CustAccountNo='" + txt_cardnum.Text + "',CustAddress='" + txt_address.Text + "',CustPOBox='" + txt_postalcode.Text + "' where CustID='" + id + "'";
cmd2.ExecuteNonQuery();
con.Close();
}
Help will be much appreciated. THANKS!
After debugging the result i am getting is this
cmd2.CommandText "update Customers set CustName='Umer Farooq',CustCNIC='42101555555555',Email='adada#gmail.com',CustAccountNo='0',CustAddress='',CustPOBox='0' where CustID='6'" string
Here Account Number And POBOX is 0 and address is going as empty string. But i have filled the text fields
First thing to do to fix this is to use good ADO techniques, using SqlParameters for the passed in values; and not the risky SQL Injection method of concatenating strings together.
This first portion does just that. I have added in the int sqlRA variable to read the results of the non-query, which will return Rows Affected by the query. This is wrapped in a simple try...catch routine to set the value to negative 1 on any error. Other error handling is up to you. That makes your code look something like this:
cmd1.Parameters.AddWithValue("#SessionUser", Session["User"]);
int id = Convert.ToInt32(cmd1.ExecuteScalar());
cmd2.CommandType = CommandType.Text;
cmd2.CommandText = "UPDATE Customers SET CustName = #CustName, CustCNIC = #CustCNIC, Email = #Email, CustAccountNo = #CustAccountNo, CustAddress = #CustAddress, CustPOBox = #CustPOBox WHERE (CustID = #CustID)";
cmd2.Parameters.AddWithValue("#CustName", txt_name.Text);
cmd2.Parameters.AddWithValue("#CustCNIC", Cnic.Text);
cmd2.Parameters.AddWithValue("#Email", txt_emailaddress.Text);
cmd2.Parameters.AddWithValue("#CustAccountNo", txt_cardnum.Text);
cmd2.Parameters.AddWithValue("#CustAddress", txt_address.Text);
cmd2.Parameters.AddWithValue("#CustPOBox", txt_postalcode.Text);
cmd2.Parameters.AddWithValue("#CustID", id);
int sqlRA
try { sqlRA = cmd2.ExecuteNonQuery(); }
catch (Exception ex) {
sqlRA = -1;
// your error handling
}
/* sqlRA values explained
-1 : Error occurred
0 : Record not found
1 : 1 Record updated
>1 :Multiple records updated
*/
Now reading through your code, all we are doing with the first query is mapping the Session["User"] to id, and then using that id in the second query to do the update, and that Username is not updated in the second. Waste of a query most likely, as we could use the Session["User"] to do the update. That will bring you down to this query, and still bring back that Rows Affected value back:
cmd0.CommandType = CommandType.Text;
cmd0.CommandText = "UPDATE Customers SET CustName = #CustName, CustCNIC = #CustCNIC, Email = #Email, CustAccountNo = #CustAccountNo, CustAddress = #CustAddress, CustPOBox = #CustPOBox WHERE (UserName = #SessionUser)";
cmd0.Parameters.AddWithValue("#CustName", txt_name.Text);
cmd0.Parameters.AddWithValue("#CustCNIC", Cnic.Text);
cmd0.Parameters.AddWithValue("#Email", txt_emailaddress.Text);
cmd0.Parameters.AddWithValue("#CustAccountNo", txt_cardnum.Text);
cmd0.Parameters.AddWithValue("#CustAddress", txt_address.Text);
cmd0.Parameters.AddWithValue("#CustPOBox", txt_postalcode.Text);
cmd0.Parameters.AddWithValue("#SessionUser", Session["User"]);
int sqlRA
try { sqlRA = cmd0.ExecuteNonQuery(); }
catch (Exception ex) {
sqlRA = -1;
// your error handling
}
/* sqlRA values explained
-1 : Error occurred
0 : Record not found
1 : 1 Record updated
>1 :Multiple records updated
*/
When BtnSubmit fires the event, the code in the Page_Load runs before the codes in BtnSubmit, replacing the values placed in the TextBox with the values from the Database before the Update takes place.

C# SQL result as variable

On my main form I have queried the user id on submission. Once I save the id to a variable how can I call it on another windows form in the same application?
This is what I have so far
private void btnLogin_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection("Data Source=.database.windows.net;Initial Catalog=userlogins;Persist Security Info=True;User ID=****;Password=****");
SqlDataAdapter sda = new SqlDataAdapter("Select ID from users where username='" + txtUsername.Text + "' and password='" + txtPassword.Text + "' ", con);
SqlCommand cmd = con.CreateCommand();
con.Open();
// save SQL ID to variable
cmd.CommandText = "Select Id from users where username = '" + txtUsername.Text + "'";
int sqlid = ((int)cmd.ExecuteScalar());
Any information would be appreciated, I really need the ID on multiple other pages!
If you are using the ExecuteScalar() method, it's important to remember that this will only return the contents of the first cell in your results, so it can generally help to use in conjunction with a TOP 1 statement.
Additionally, you should consider refactoring your code to use parameterization, which should help avoid nastiness like SQL Injection and will also help mitigate any syntax issues :
// Build your connection
using(var con = new SqlConnection("your-connection-string"))
{
// Build your query
var query = "SELECT TOP 1 ID FROM users WHERE username = #username AND password = #password";
// Build a command to execute your query
using(var cmd = new SqlCommand(con,query))
{
// Open your connection
con.Open();
// Add your parameters
cmd.Parameters.AddWithValue("#username", txtUsername.Text);
cmd.Parameters.AddWithValue("#password", txtPassword.Text);
// Get your ID
var sqlid = Convert.ToInt32(cmd.ExecuteScalar());
// Do something here
}
}
One way to do this is with events:
public class IdChangedEventArgs : EventArgs
{
int ChangedId {get;set;};
}
public delegate void IdChangedEventHandler(object sender, IdChangedEventArgs e);
public event IdChangedEventHandler IdChangedEvent;
private void btnLogin_Click(object sender, EventArgs e)
{
int sqlid = ((int)cmd.ExecuteScalar());
IdChangedEvent(this, new IdChangedEventArgs {ChangedId = sqlid;} );
}
In each of your interested forms, subscribe to the events. When handled, update your GUI however you want.

Why I get syntax error in this update statement?

I wanted to update a table in my m/s access database where my the user entered a new password in order to replace the old one but i have syntax error in the update statement. Please help!
public partial class resetPassword : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void SubmitButton_Click(object sender, EventArgs e)
{
string userName = (string) Session["username"];
string str = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\inetpub\wwwroot\JetStar\database\JetstarDb.accdb";
var con = new OleDbConnection(str);
con.Open();
string pwd = Request.Form["conPassword"];
OleDbCommand cmd = new OleDbCommand("UPDATE [users] SET password = '" + pwd + "' WHERE username = '" + userName + "'", con);
try
{
cmd.ExecuteNonQuery();
MessageBox.Show("Your password has been changed successfully.");
}
catch (Exception ex)
{
Response.Write(ex.Message);
}
finally
{
con.Close();
}
}
}
Probably this happends because password is a reserved keyword on Microsoft Access. You should use it with square brackets as [password]
But more important
You should always use parameterized queries. This kind of string concatenations are open for SQL Injection attacks.
Don't store your passwords as a plain text. Read: Best way to store password in database
Use using statement to dispose your OleDbConnection and OleDbCommand.
using(OleDbConnection con = new OleDbConnection(str))
using(OleDbCommand cmd = con.CreateCommand())
{
cmd.CommandText = "UPDATE [users] SET [password] = ? WHERE username = ?";
cmd.Parameters.Add("pass", OleDbType.VarChar).Value = pwd;
cmd.Parameters.Add("user", OleDbType.VarChar).Value = userName;
con.Open();
try
{
cmd.ExecuteNonQuery();
MessageBox.Show("Your password has been changed successfully.");
}
catch (Exception ex)
{
Response.Write(ex.Message);
}
}
92.3% (a) of all DB problems become obvious if you just print the command before you use it, and read the error message.
So replace:
OleDbCommand cmd = new OleDbCommand("UPDATE [users] SET password = '" + pwd + "' WHERE username = '" + userName + "'", con);
with something like:
String s = "UPDATE [users] SET password = '" + pwd + "' WHERE username = '" + userName + "'";
Console.WriteLine(s);
OleDbCommand cmd = new OleDbCommand(s, con);
Then post the results of:
Response.Write(ex.Message);
for all to see, and examine what it tells you very carefully.
(a) A statistic I just plucked out of nowhere - actual value may be wildly different.

Checking if a user exists, and stopping a database insert (access database)

I just don't know how to check if the users exists in the database and stop it from inserting a new row to the db (which will cause an error as I set the user to be a primary key)
protected void Button1_Click1(object sender, EventArgs e)
{
{
OleDbConnection myconnection = new OleDbConnection();
myconnection.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=|DataDirectory|Event.mdb";
myconnection.Open();
OleDbCommand myCommand = new OleDbCommand();
myCommand.Connection = myconnection;
myCommand.CommandType = CommandType.Text;
string query = string.Format("SELECT COUNT(*) FROM users WHERE uname = '{0}'");
myCommand.CommandText = query;
try
{
int amountOfUsers = (int)myCommand.ExecuteScalar();
if (amountOfUsers < 1)
{
String myQuery = "insert into users (uname,upassword,email,type) Values ('" + UserName.Text + "','" + Password.Text + "' ,'" + Email.Text + "',' user');";
myCommand.CommandText = myQuery;
myCommand.ExecuteNonQuery();
Label1.Text = "user registered";
}
else
{
Label1.Text = "user already exists";
UserName.Text = "";
Email.Text = "";
}
}
finally
{
myconnection.Close();
}
}
}
correct your query:
query = string.Format("SELECT COUNT(*) FROM users WHERE uname = '{0}'" ,UserName.Text );
Your question isn't clear at all but I can suggest a few things..
First of all, I think you forget to use your uname as a second parameter in your:
string query = string.Format("SELECT COUNT(*) FROM users WHERE uname = '{0}'");
line. You used {0} but never point any value to this parameter. (I assume you don't have a username called {0}) Like;
string query = string.Format("SELECT COUNT(*) FROM users WHERE uname = '{0}'", UserName.Text);
As a second, please always use parameterized queries. This kind of string concatenations are open for SQL Injection attakcs.
Like;
String myQuery = "insert into users (uname,upassword,email,type) Values (#uname, #upassword, #email, #type)";
OleDbCommand myCommand = new OleDbCommand(myQuery);
myCommand.Parameters.AddWithValue("#uname", UserName.Text);
myCommand.Parameters.AddWithValue("#upassword", Password.Text);
myCommand.Parameters.AddWithValue("#uname", Email.Text);
myCommand.Parameters.AddWithValue("#uname", "user");
i want to check if the username in UserName.Text is availble in the
data base or no and if it does i want to stop from inserting new data
Than you should use SELECT first to check your username is exist in your database or not like;
string query = string.Format("SELECT * FROM users WHERE uname = '{0}'", UserName.Text);
OleDbCommand myCommand = new OleDbCommand();
myCommand.CommandText = query;
SqlDataReader reader = myCommand.ExecuteReader();
if(reader.HasRows)
{
//Your username exist in your database
}
else
{
//Doesn't exist
}
you have missing the parameter uname , you have pass the text of UserName textbox to uname
for eg
"SELECT COUNT(*) FROM users WHERE uname='" + UserName.Text +"'

Categories