I currently have an asp.net website. However I have noticed that in my Registration Page, users are able to register multiple times using the same username. As such, I am wondering if there is a way to prevent the users from registering multiple times using the same username.
I do know that i can set one column in my database to have a primary key... But what do i do if i want to have multiple columns to have primary keys?
This is my Insert Code....
MySqlCommand command = mcon.CreateCommand();
mcon.Open();
command.CommandText = "insert into pointofcontact (FirstName, LastName, EmailAddress, ContactNumber, BackupContactNumber, Address, Gender, Username, Password, Status, ProfilePic) values(?firstname, ?lastname, ?emailaddress, ?contactnumber, ?backupcontactnumber, ?address, ?gender, ?username, ?password, ?status, ?image)";
command.Parameters.AddWithValue("?firstname", firstname);
command.Parameters.AddWithValue("?lastname", lastname);
command.Parameters.AddWithValue("?emailaddress", email);
command.Parameters.AddWithValue("?contactnumber", mobileNumber);
command.Parameters.AddWithValue("?backupcontactnumber", backupNumber);
command.Parameters.AddWithValue("?address", homeAddress);
command.Parameters.AddWithValue("?gender", gender);
command.Parameters.AddWithValue("?username", username);
command.Parameters.AddWithValue("?password", password);
command.Parameters.AddWithValue("?status", status);
command.Parameters.AddWithValue("?image", imageName);
command.ExecuteNonQuery();
mcon.Close();
MySqlDataReader reader = null;
mcon.Open();
MySqlCommand command2 = mcon.CreateCommand();
command2.CommandText = "select * from pointofcontact where Username = ?username";
command2.Parameters.AddWithValue("?username", tbUsername.Text);
reader = command2.ExecuteReader();
if (reader != null && reader.HasRows)
{
lblValidate.Text = "Username already exists.";
}
Response.Redirect("IndexAfterLogin1.aspx");
The data that the user inputs is able to be inserted into my MySQL Database, but the inputted data is able to be repeated for Username and Email fields for different users, and I do not want that to happen.
For that purpose you can add a unique key in table else create a function to check in database before inserting that's it
Make the field username as primary or unique key. It will not allow duplicate entries for that field
Order your code as follows:
try
{
MySqlDataReader reader = null;
mcon.Open();
MySqlCommand command2 = mcon.CreateCommand();
command2.CommandText = "select * from pointofcontact where Username = ?username";
command2.Parameters.AddWithValue("?username", tbUsername.Text);
reader = command2.ExecuteReader();
if (reader != null && reader.HasRows)
{
lblValidate.Text = "Username already exists.";
**return;**
}
else
{
MySqlCommand command = mcon.CreateCommand();
command.CommandText = "insert into pointofcontact (FirstName, LastName, EmailAddress, ContactNumber, BackupContactNumber, Address, Gender, Username, Password, Status, ProfilePic) values(?firstname, ?lastname, ?emailaddress, ?contactnumber, ?backupcontactnumber, ?address, ?gender, ?username, ?password, ?status, ?image)";
command.Parameters.AddWithValue("?firstname", firstname);
command.Parameters.AddWithValue("?lastname", lastname);
command.Parameters.AddWithValue("?emailaddress", email);
command.Parameters.AddWithValue("?contactnumber", mobileNumber);
command.Parameters.AddWithValue("?backupcontactnumber", backupNumber);
command.Parameters.AddWithValue("?address", homeAddress);
command.Parameters.AddWithValue("?gender", gender);
command.Parameters.AddWithValue("?username", username);
command.Parameters.AddWithValue("?password", password);
command.Parameters.AddWithValue("?status", status);
command.Parameters.AddWithValue("?image", imageName);
command.ExecuteNonQuery();
}
}
catch
{
....
}
finally
{
mycon.Close();
}
Related
MySqlConnection con = new MySqlConnection(connectionstr);
con.Open();
string insertid = "SELECT UserID FROM login WHERE username =#U";
MySqlCommand cmd2 = new MySqlCommand(insertid, con);
cmd2.Parameters.AddWithValue("#U", username);
MySqlDataReader idread = cmd2.ExecuteReader();
idread.Read();
string id;
if (idread.HasRows==true)
{
id = idread.GetString(0);
string insertid2 = "INSERT INTO managementtest.fulldetails(UserID) VALUES(#I);";
MySqlCommand cmd3 = new MySqlCommand(insertid2, con);
cmd3.Parameters.AddWithValue("#I", id);
MessageBox.Show("Detail Profile Created. User ID # " + id , "Success", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
I have tried running this code. Everything runs fine but the value of id is not added into MySQL Database. I have checked the spelling of table name and all. It isn't working. string username is predefined and holds a specific value from a textbox.
you forgot this
cmd3.CommandType = CommandType.Text;
cmd3.ExecuteNonQuery();
I am currently working with SQL database and my assignment is to make a registration form. I have got the registration form to work but I need to check if username have already been taken. In my code Username is in the form of Emails. The code I have works, but as it is, multiple usernames are allowed.
HEre is my code:
protected void registerUser(Object src, EventArgs e)
{
Response.Write("you have connected to your .cs page add records");
get_connection();
try
{
connection.Open();
command = new SqlCommand("INSERT INTO subscribers (FirstName, LastName, Email, Password)" +
" VALUES (#FirstName, #LastName, #Email, #Password)", connection);
command.Parameters.AddWithValue("#FirstName", txtFirstName.Text);
command.Parameters.AddWithValue("#LastName", txtLastName.Text);
command.Parameters.AddWithValue("#Email", txtEmail.Text);
command.Parameters.AddWithValue("#Password", txtPassword.Text);
command.ExecuteNonQuery();
//connection.Close();
}
catch(Exception err)
{
lblInfo.Text = "Error reading the database. ";
lblInfo.Text += err.Message;
}
finally
{
connection.Close();
lblInfo.Text += "<br /><b>Record has been added</b>";
//lblInfo.Text = "<b>Server Version:</b> " + connection.ServerVersion;
lblInfo.Text += "<br /><b>Connection Is:</b> " + connection.State.ToString();
}
}
To check if the username had already been taken, I was thinking about using an "If Then" statement within the "try" area but am unsure what coding I would need. Any help or advice would be appreciated.
You can write something like this:
string cmdText = #"IF NOT EXISTS(SELECT 1 FROM subscribers where Email = #Email)
INSERT INTO subscribers (FirstName, LastName, Email, Password)
VALUES (#FirstName, #LastName, #Email, #Password)"
command = new SqlCommand(cmdText, connection);
......
You can try this code :
string sqlQuery = "IF NOT EXISTS (SELECT 1 FROM subscribers where Email = #Email)
BEGIN
INSERT INTO subscribers (FirstName, LastName, Email, Password) VALUES (#FirstName, #LastName, #Email, #Password)
SELECT SCOPE_IDENTITY()
END
ELSE SELECT 0"
using (command = new SqlCommand())
{
command.CommandText = sqlQuery;
command.Parameters.AddWithValue("#FirstName", txtFirstName.Text);
command.Parameters.AddWithValue("#LastName", txtLastName.Text);
command.Parameters.AddWithValue("#Email", txtEmail.Text);
command.Parameters.AddWithValue("#Password", txtPassword.Text);
connection.Open();
var res = (int)cmd.ExecuteScalar();
connection.Close();
}
if a result is 0 then already exists otherwise new record inserted.
I'm trying to make a function to password reset. I have a database with 3 columns: Username, Password, Email.
I want to update the password for a specific email address.
I used the following code:
try
{
SqlConnection connection = new SqlConnection();
connection.ConnectionString = "Server=WIN2CNG9\\SQLEXPRESS;Database=OOPII_Project;Trusted_Connection=true";
SqlCommand cmd = new SqlCommand();
cmd.Connection = connection;
cmd.CommandText = "UPDATE Users SET Password = #pass WHERE Email = #email";
cmd.Parameters.AddWithValue("#pass", md5Kod);
cmd.Parameters.AddWithValue("#email", Email);
connection.Open();
cmd.ExecuteNonQuery();
MessageBox.Show("Ok");
connection.Close();
this.Close();
}
But nothing happens in my database.
I tried also to make a simple insert command:
cmd.CommandText = "INSERT INTO Users (Username, Password, Email) VALUES ('a', 'b', 'c')";
Here the same result, nothing happens.
Where is my mistake?
Thank you!
This line
cmd.Parameters.AddWithValue("#fn", Email);
should change to this
cmd.Parameters.AddWithValue("#email", Email);
You have two parameters, #pass and #email. While for the first one you pass a value, for the second you don't.
I have an Object Query in MS Access (getUserLogin) that will execute the following:
PARAMETERS prmUsername Text, prmPassword Text;
SELECT ID, LastName, FirstName, MiddleName
FROM tblUsers
WHERE Username = [prmUsername] AND Password = [prmPassword];
I have a method in my C# to execute the Object Query in MS Access (getUserLogin).
public bool login(string username, string password)
{
com = new OdbcCommand("EXEC getUserLogin", con);
com.CommandType = CommandType.StoredProcedure;
com.Parameters.Add("prmUsername", OdbcType.Text).Value = username;
com.Parameters.Add("prmPassword", OdbcType.Text).Value = password;
con.Open();
rea = com.ExecuteReader(); //OdbcException goes here
if (rea.HasRows == true)
return true;
else
return false;
}
I'm getting this OdbcException:
ERROR [07002] [Microsoft][ODBC Microsoft Access Driver] Too few
parameters. Expected 2.
Your first problem is that your query uses parameter names that are the same as the corresponding field names. If you try to run your query in Access it will prompt you for the "Username" and "Password" parameters and then return all rows in tblUsers regardless of the parameter values you enter. That is because when the Access SQL parser processes
... WHERE Username = [Username] AND Password = [Password]
... it interprets [Username] and [Password] as field names, not parameter names, and the result is the same as
... WHERE True AND True
So, the first thing you need to do is change your parameter names. One relatively common convention is to use a "prm" prefix for parameter names, so your query would be
PARAMETERS prmUsername Text, prmPassword Text;
SELECT [ID], [LastName], [FirstName], [MiddleName]
FROM [tblUsers]
WHERE [Username] = [prmUsername] AND [Password] = [prmPassword];
Now, to pass your parameter values in your C# application you need to use System.Data.OleDb (not .Odbc) with code something like this
using (var con = new OleDbConnection(myConnectionString))
{
con.Open();
using (var cmd = new OleDbCommand())
{
cmd.Connection = con;
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "loginQuery";
cmd.Parameters.Add("prmUsername", OleDbType.VarWChar).Value = "eric";
cmd.Parameters.Add("prmPassword", OleDbType.VarWChar).Value = "abcdefg";
using (OleDbDataReader rdr = cmd.ExecuteReader())
{
if (rdr.Read())
{
Console.WriteLine("Row found: ID = {0}", rdr["ID"]);
}
else
{
Console.WriteLine("Row not found.");
}
}
}
}
I am a new C# and ASP.NET developer. I am developing a simple intranet booking management system for my company. I want the system to check if the user has a booking before in the event or not.
I have the following database design:
Users Table: UserID, Name
Events Table: ID, Title, Description, Location, NumberOfSeats, StartDateTime, EndDateTime, IsActive
Booking Table: BookingID, EventID, UserID
What I did so far is checking the UserID (when the user clicks on Booking button) if it is in the Users Table or not. If not, he will be added automatically to the database. Now I want to check if he has a booking in that event or not by checking BookingDetails table but I don't know how to do that?
Could you please help me in designing this condition?
Here's my method for checking the username:
protected void checkUserID(string userID) {
int eventID = Convert.ToInt32(HiddenField1.Value);
string NetworkID = userID;
string Name = Service.(".......");
string BadgeNo = Service("ffffff");
string DepartmentCode = Service("ffffff");
string connString = "Data Source=localhost\\sqlexpress;Initial Catalog=RegistrationSysDB;Integrated Security=True;";
//if the user is not in the system database, add him
if (Security.isExisted(userID) == false)
{
//string connString = "Data Source=localhost\\sqlexpress;Initial Catalog=RegistrationSysDB;Integrated Security=True;";
string insertCommand = "INSERT INTO Users (NetworkID, Name, BadgeNo, DepartmentCode) values (#NetworkID, #Name, #BadgeNo, #DepartmentCode)";
using(SqlConnection conn = new SqlConnection(connString))
{
//Open DB Connection
conn.Open();
using(SqlCommand cmd = new SqlCommand(insertCommand, conn))
{
cmd.Parameters.Clear();
cmd.Parameters.AddWithValue("#NetworkID", NetworkID);
cmd.Parameters.AddWithValue("#Name", Name);
cmd.Parameters.AddWithValue("#BadgeNo", BadgeNo);
cmd.Parameters.AddWithValue("#DepartmentCode", DepartmentCode);
cmd.ExecuteNonQuery();
}
conn.Close();
}
}
}
You haven't set the parameters on the SELECT command, here is the revised code below.
string insertBooking = "INSERT INTO BookingDetails (EventID, NetworkID) values (#EventID, #NetworkID)";
string selectCommand = "SELECT count(*) as UserBookings FROM BookingDetails WHERE NetworkID = #NetworkID AND EventID = #EventID";
using (SqlConnection conn = new SqlConnection(connString))
{
//Open DB Connection
conn.Open();
using (SqlCommand cmd = new SqlCommand(selectCommand, conn))
{
cmd.Parameters.Clear();
cmd.Parameters.AddWithValue("#EventID", eventID);
cmd.Parameters.AddWithValue("#NetworkID", NetworkID);
if ((int)cmd.ExecuteScalar() == 0)
{
SqlCommand cmd2 = new SqlCommand(insertBooking, conn);
cmd2.Parameters.Clear();
cmd2.Parameters.AddWithValue("#EventID", eventID);
cmd2.Parameters.AddWithValue("#NetworkID", NetworkID);
cmd2.ExecuteNonQuery();
}
}
//Close the connection
conn.Close();
}
Your Booking table has a foreign key of UserID
Booking Table: BookingID, EventID, UserID
You can get a count of records against a particular UserID and if the count is greater than 0 that means the user has the booking. Your query may be:
Select count(*) as UserBookings from Bookings where UserID = #UserID;
where #UserID is the UserID you want to compare with, and UserBookings will give you the count