Paolo Duhaylungsod Paolo Duhaylungsod - 6 months ago 26
SQL Question

if statement on session and Id value in sql asp.net

i want to compare my session value to my Id value using if statement.
so far i got this:

string strConnString = "Data Source = 'PAULO'; Initial Catalog=ShoppingCartDB;Integrated Security =True";
string str;
SqlCommand com;
protected void Page_Load(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(strConnString);

con.Open();
str = "select * from CustomerDetails Where CustomerName = '"+Session["New"].ToString()+"'";
com = new SqlCommand(str, con);
SqlDataReader reader = com.ExecuteReader();
List<string> ListOfId = new List<string>();
while (reader.Read())
{

ListOfId.Add(reader["Id"].ToString());
}
if (!IsPostBack)
{

if (Session["New"].ToString() == Request.QueryString["Id"])
{
Success
}
else
{
error
}


What i want to happen is when the session value ("username") has no equivalent value of id in sql, it will be redirected to an error page.

enter image description here

Like in the picture above, these id values are from the username "faufao".
if session("faufao" = "13")
, it will continue. Otherwise if the username is faufao, and id value is 4, it will proceed to error page.

On the picture below. i substituted the label values to the session and ID query string. faufao(session) has the 14(query) value in the database so it should proceed. same goes with 13 15 16 17 18 19 etc. Other values that are not in the faufao(session) username will redirect to error.

enter image description here

The code is working. It catches the session and the id value (tried it in labels). My problem now is how to compare them.

My code:

if (Session["New"].ToString() == Request.QueryString["Id"])
{
Proceed
}
else
{
error
}


It seems like i am lacking something here. Because it always redirects me to error page even though session:faufao has the query string of 13.

tried your code and clicked on ID 13

enter image description here

faufao has the id value of 13, but still redirects to error page.

Answer

There are a few things that are worth addressing in your existing code, which will hopefully resolve some of your issues.

Use Parameterization, Not Concatenation

You should take advantage of .NET's built-in support for handling SQL parameters, which can help you avoid nasty things like SQL Injection attacks and improper syntax when concatenating your query strings :

using(var con = new SqlConnection(strConnString))
{
    con.Open();
    var query = "SELECT * FROM CustomerDetails WHERE CustomerName = @name";
    using(var com = new SqlCommand(query,con))
    {
        // This will help avoid any nastiness with your existing syntax
        com.Parameters.AddWithValue("@name", Convert.ToString(Session["New"]));

        // Execute your query here
    }
}

Possible Logic Issue

You mention wanting to compare your Session value versus a value from your QueryString. If that is the case, you don't need to hit the database at all as both of those values should be present when this area is hit :

if(Convert.ToString(Session["New"]) != Convert.ToString(Request["Id"]))
{
      // The two values are different, so redirect
      Response.Redirect("Error.aspx");
}

What i want to happen is when the session value ("username") has no equivalent value of id in sql, it will be redirected to an error page.

If that is the case, then after executing your query, you could simply check if any ID values were found and if not, redirect :

if(!ListOfIds.Any())
{
      // No matches were found, redirect
      Response.Redirect("Error.aspx");
}

If you want to use the value that is returned from your database or check if it is one of multiple values that exist, you can do that as well :

// Assuming you have all of your ID values within your list after executing
if(!ListOfId.Contains(Convert.ToString(Session["New"]))
{
     // If your IDs don't contain your Session value, redirect
     Response.Redirect("Error.aspx");
}

UPDATE

Based on your update, it sounds like you simply want to see if a certain combination of user/id exists within the database. If that is the case, you could just update your query accordingly :

using(var con = new SqlConnection(strConnString))
{
    con.Open();
    var query = "SELECT * FROM CustomerDetails WHERE CustomerName = @name AND ID = @id";
    using(var com = new SqlCommand(query,con))
    {
        // This will help avoid any nastiness with your existing syntax
        com.Parameters.AddWithValue("@name", Convert.ToString(Session["New"]));
        com.Parameters.AddWithValue("@id",Convert.ToInt32(Request["Id"]));

        // Execute your query
        using(var reader = com.ExecuteReader())
        {
              if(!reader.HasRows)
              {
                  // Redirect
                  Response.Redirect("Error.aspx");
              }  
              // Do something here
        }
    }
}