Jump to content


Check out our Community Blogs

Register and join over 40,000 other developers!


Recent Status Updates

View All Updates

Photo
- - - - -

Login Form and a Database

sql asp web login

  • Please log in to reply
5 replies to this topic

#1 noname111

noname111

    CC Resident

  • Advanced Member
  • PipPipPipPip
  • 79 posts
  • Location:Ohio
  • Programming Language:C#, JavaScript, Others
  • Learning:C++, Transact-SQL, Others

Posted 14 October 2012 - 01:06 PM

I am working on a webpage login form and it has been a while since I did any sql connection from c#. I have set up two text boxes, one for the username and one for the password as well as a button to initialize the login. I have set up the sql connection and I try to compare the textbox text with the string stored in the database, but it comes back saying that it isn't true. For my code below, I am just trying to see if it is comparing the two strings or not before I proceed any further.

protected void LoginButton_Click(object sender, EventArgs e)
	    {
		    using (SqlConnection Con = new SqlConnection(Connection))
		    {
			    if (string.IsNullOrEmpty(Userbox.Text))
			    {
				    ErrorLabel.Text = "Please enter a username";
				    Userbox.Focus();
				    return;
			    }							 
			   
			    SqlCommand cmd = new SqlCommand("select * from Users where user=@userstring", Con);			   
			    cmd.Parameters.AddWithValue("@userstring", Userbox.Text);
			    Con.Open();
				    if (Userbox.Text == cmd.ToString())
				    {
					    ErrorLabel.Text = "login correct";
				    }
				    else
				    {
					    ErrorLabel.Text = "Could not retrieve your name";
				    }
		    }
	    }

  • 0

#2 logicPwn

logicPwn

    CC Addict

  • Advanced Member
  • PipPipPipPipPip
  • 177 posts
  • Location:Fresno, CA
  • Programming Language:C#, PHP, JavaScript, PL/SQL

Posted 14 October 2012 - 01:49 PM

Here is my AJAX login

HTML form
  </div>
  <div id="main">
	  <div class="divider"></div>
	  <div>
		  <h2>Admin Login</h2>
		  <form class="login-form">
			  <label>Username:</label><br />
			  <input type="text" name="username" id="username" />
			  <br />
			  <label>Password:</label><br />
			  <input type="password" name="password" id="password" />
			  <br />
			  <input type="button" value="Send" onclick="loginAJAX();" class="submit-button" />
		  </form>
	  </div>
	  <div class="divider"></div>
</div>

Javascript function
$(document).ready(function() {
    $("#email").focusout(function() {
	    if ($("#email").val() == "") {
		    $("#email").css("background-color", "#F5A9A9");
	    }
    }).keydown(function () { $("#email").css("background-color", "#FFFFFF"); });
    $("#password").focusout(function() {
	    if ($("#password").val() == "") {
		    $("#password").css("background-color", "#F5A9A9");
	    }
    }).keydown(function () { $("#password").css("background-color", "#FFFFFF"); });
});
function loginAJAX() {
    if ($("#email").val() == "") {
	    alert("Your email is required.");
	    $("#email").focus();
	    return;
    }
    if ($("#password").val() == "") {
	    alert("Your password is required.");
	    $("#password").focus();
	    return;
    }
    //
    $.post("ajax/Login.php", $("form").serialize(), function(json) {
	    if (json.result == "error") {
		    alert(json.message);
	    } else if (json.result == "success") {
		    document.location.href = "index.php?page=admin";
	    }
    }, "json");
}

PHP script
<?php
header('Cache-Control: no-store, no-cache, must-revalidate, private, post-check=0, pre-check=0');
header('Pragma: no-cache');
header("content-type: application/json; charset=utf-8");
$db = new mysqli("localhost", "", "", "");
if (mysqli_connect_errno()) { returnError("mysql_connect_error", $db->error); }
if (!isset($_POST['username'])) { returnError("username_empty", "Username not provided."); }
else { $username = $db->escape_string($_POST['username']); }
if (!isset($_POST['password'])) { returnError("password_empty", "Password not provided."); }
else { $password = $_POST['password']; }
if ($result = $db->query("SELECT * FROM `users` WHERE `username`='" . $username . "' LIMIT 1")) {
    if ($db->affected_rows > 0) {
	    $user = $result->fetch_assoc();
	    if ($password == $user['password']) {
		    $uid = uniqid("", true);
		    setcookie("logged_in", $user['id'], time() + 604800, "/");
		    setcookie("security_check", $uid, time() + 604800, "/");
		    $db->query("UPDATE users SET security_code='" . $uid . "' WHERE id='" . $user['id'] . "'");
		    if ($db->affected_rows == 1) { returnSuccess("Successfully logged in."); }
		    else { returnError("mysql_error", "Couldn't write security code to database.");  }
	    } else { returnError("password_incorrect", "Password is incorrect."); }
    } else { returnError("not_registered", "Username doesn't exist."); }
} else { returnError("mysql_error", $db->error); }
function returnError($err, $msg) {
    $error = array();
    $error["result"]  = "error";
    $error["error"]   = $err;
    $error["message"] = $msg;
    //
    die(json_encode($error));
}
function returnSuccess($msg) {
    $success = array();
    $success["result"]  = "success";
    $success["message"] = $msg;
    //
    die(json_encode($success));
}
?>

  • 0
"Always code as if the guy who ends up maintaining your code will be a violent psychopath who knows where you live."
- Martin Golding

#3 noname111

noname111

    CC Resident

  • Advanced Member
  • PipPipPipPip
  • 79 posts
  • Location:Ohio
  • Programming Language:C#, JavaScript, Others
  • Learning:C++, Transact-SQL, Others

Posted 14 October 2012 - 05:24 PM

Sorry, I forgot to mention that I am working with C# and SQL. I didn't notice until after you posted. I edited it with the code that I currently have a little bit ago.
  • 0

#4 logicPwn

logicPwn

    CC Addict

  • Advanced Member
  • PipPipPipPipPip
  • 177 posts
  • Location:Fresno, CA
  • Programming Language:C#, PHP, JavaScript, PL/SQL

Posted 14 October 2012 - 06:31 PM

Oh in that case I usually make a php script to do the db work for me. That way whoever uses your application can't cap the network traffic and grab your mysql password.
  • 0
"Always code as if the guy who ends up maintaining your code will be a violent psychopath who knows where you live."
- Martin Golding

#5 VNFox

VNFox

    CC Devotee

  • Senior Member
  • PipPipPipPipPipPip
  • 648 posts
  • Programming Language:C#, PHP
  • Learning:Assembly

Posted 14 October 2012 - 08:15 PM

While looking at your code ... I see that you open the connection but u didn't call the reader, something like that:

cmd.ExecuteReader();

Here you can check more info on it:
http://www.java2s.co...eanddeleteC.htm
  • 0

www.pickmike.com
I don't just develop software. I find solutions to your business needs.


#6 lespauled

lespauled

    CC Leader

  • Expert Member
  • PipPipPipPipPipPipPip
  • 1360 posts
  • Programming Language:C, C++, C#, JavaScript, PL/SQL, Delphi/Object Pascal, Visual Basic .NET, Pascal, Transact-SQL, Bash

Posted 15 October 2012 - 10:26 AM

You are opening the connection, but not doing anything after that.

I recommend getting your database code out of your UI and into its own class.

I usually do something quick, like the code below that uses a stored procedure. You can change it to use your sql statement.

public static DataTable GetLoginCredentials(string userID)
{
 DataTable retVal = null;
 DataSet dstRetVal = new DataSet();
 using (SqlConnection conn = new SqlConnection(connectionString))
 {
  if (conn.State != ConnectionState.Open)
   conn.Open();
  // for speed purposes, use the SP that uses equals vs like when possible.
  string storedProc = "usp_GetLoginCredentials";
  SqlCommand cmd = new SqlCommand(storedProc, conn);
  cmd.CommandType = CommandType.StoredProcedure;
  cmd.Parameters.Add(new SqlParameter("@UserID", userID));
  SqlDataAdapter da = new SqlDataAdapter(cmd);
  da.Fill(dstRetVal);
 }
 if (dstRetVal.Tables.Count > 0)
  retVal = dstRetVal.Tables[0];
 return retVal;
}

Then the call would be something like:

DataTable dt = GetLoginCredentials(userID);

if(null == dt)
// user is not validated

...


LOGICPWN, Doing something in another language is the last thing anyone should do.

Just a note: I changed this code from an actual method, thus some of it might not make much sense, like the connection open verification. It can be left out here.
  • 0
My Blog: http://forum.codecal...699-blog-77241/
"Women and Music: I'm always amazed by other people's choices." - David Lee Roth





Also tagged with one or more of these keywords: sql, asp, web, login

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download