I have a table named users two of it's fields are login and name.
These fields can not be duplicate.
When the user are going to create a new registration, I already made a method to check if that name/login already exists or not.
But the user can also edit his login/name.
When the user enters on the page to edit his registration data, it already fills the fields with the current data.
I have 3 fields [NAME] [EMAIL] [LOGIN].
The user can edit only 1 of this or all of them at once ...
How may I create a method to check if that name/loginalready exists or not when he try to edit it ? Maybe a Query ? A select count on the login then on the name field ?
--UPDATE--
here's my solution
You should leave this up to the database system you are using and handle any errors it may throw. All database systems (Access, Oracle, MS SQL, etc) allow you to mark a table field as being Unique. This means that the table can only hold one records with a field(s) with that value. If you try to add more than one record with a same field, you will be thrown an error. Your application should catch that error and alert the user. If you post what kind of database system you are using I can show you how to do this.
Edit:
Heres is an example. This uses the SqlClient.SqlException exception class. I'm not sure what the error code is for unique constraints but I added a variable in the catch that you can place a break point on to get. Just change the if statement to match that error code:
Try
'your database insert attempt here
Catch ex As SqlClient.SqlException
Dim sqlErrorNumber = ex.ErrorCode
If (sqlErrorNumber = 1) Then
Me.lblWarning.Text = "Please select a unique ID"
Me.lblWarning.Visible = True
Me.lblWarning.ForeColor = Drawing.Color.Red
Me.lblWarning.Font.Bold = True
End If
End Try
In the aspx page:
<asp:Label ID="lblWarning" runat="server" Visible="false"></asp:Label>
What is your primary key here?
I suggest, Adding new identity column to your table will solve the issue.
You can edit the row based on the identity column.
For Ex: Add [UserID] field and made it unique identity column. then perform update operations based on userid in where clause.
You should use unique fields in your database, try catch in php or asp and ajax technique to get sure that the fields are filled or not with the informations that are you typing now.
if you don't have a column ID or if username column is not set like UNIQUE you can use this function :
function user_exists($username){
$username = sanitize($username); // sanitize
return(mysql_result(mysql_query("SELECT COUNT(user_name) FROM user_table WHERE username = '$username'"), 0) == 1) ? true : false;
}
For New Members / Or if current User wants to edit his username
this function return false if username is not registered and true if it is
Related
See Datasource Paging Issue (Revised)
for the original question.
Markus, you were kind enough to help with out with the issue of incorporating a record count into a query using a calculated datasource. I have a search form with 15 widgets - a mix of date ranges, dropdowns, text values and ._contains, ._equals, ._greaterThanOrEquals, ._lessThanOrEquals, etc.
I have tested this extensively against mySQL SQL code and it works fine.
I have now added a 16th parameter PropertyNames, which is a list with binding #datasource.query.filters.Property.PropertyName._in and Options blank. The widget on the form is hidden because it is only used for additional filtering.
Logic such as the following is used, such that a particular logged-in user can only view their own properties. So if they perform a search and the Property is not specified we do:-
if (params.param_Property === null && canViewAllRecords === false) {
console.log(params.param_PropertyNames); // correct output
ds.filters.Property.PropertyName._in = params.param_PropertyNames;
}
The record count (records.length) is correct, and if I for loop through the array of records the record set is correct.
However, on the results page the table displays a larger resultset which omits the PropertyNames filter. So if I was to search on Status 'Open' (mySQL results 50) and then I add a single value ['Property Name London SW45'] for params.param_PropertyNames the record count is 6, the records array is 6 but the datasource display is 50. So the datasource is not filtering on the property array.
Initially I tried without adding the additional parameter and form widget and just using code such as
if (params.param_Property === null && canViewAllRecords === false) {
console.log(params.param_PropertyNames); // correct output
ds.filters.Property.PropertyName._in = properties; // an array of
properties to filter out
}
But this didn't work, hence the idea of adding a form widget and an additional parameter to the calculated recordcount datasource.
If I inspect at query.parameters then I see:-
"param_Status": "Open",
"param_PropertyNames": ["Property Name London SW45"],
If I inspect query.filters:-
name=param_Status, value=Open
name=param_PropertyNames, value=[]}]}
It looks as though the filter isn't set. Even hard coding
ds.filters.Property.PropertyName._in = ['Property Name London SW45'],
I get the same reuslt.
Have you got any idea what would be causing this issue and what I can do for a workaround ?
Using a server side solution I would suggest editing both your SQL datasource query script (server side) that is supposed to filter by this property list and including the same code in your server side script for your calculated Count datasource. The code would look something like this, not knowing your exact details:
var subquery = app.models.Directory.newQuery();
subquery.filters.PrimaryEmail._equals = Session.getActiveUser().getEmail();
subquery.prefetch.Property._add();
var results = subquery.run();
if(!results[0].CanViewAllRecords) {
query.filters.Property.PropertyName._in = results[0].Property.map(function(i) {return i.PropertyName;});
}
By adding this code you are filtering your directory by your current user and prefetching the Property relation table, then you set the filter only if your user canviewallRecords is false and use JS map function to create an array of the PropertyName field in the Property table. As I stated, your code may not be exactly the same depending on how you have to retrieve your user canviewallrecords property and then of course I don't know your relation between user and Property table either, is it one-to-many or other. But this should give you an idea how to implement this on server side.
I have an ASP.net Web project that includes a form and a Database.
When a user register to the site (not from facebook) he has a username, and then when he fills the form, I can add this username to the 'username' column in the database (using User.Identity.Name). When he login using facebook, I can't do it. So I thought to use his facebook ID, since any ID is different, but I can't find a way to do it. I tried to retrieve the ID using response.id, set the value in a Label, and then to get the Label content from the codebehind to transfer it to the DB, but it didn't work. here is the code I tried:
Set the ID into the label:
function testAPI() {
FB.api('/me?fields=name,email,gender,age_range,picture.width(45).height(44),location', function (response) {
console.log('Successful login for: ' + response.name);
document.getElementById('HiddenFacebookID').innerText = response.id;
});
}
The Label:
<asp:Label ID="HiddenFacebookID" runat="server"></asp:Label>
The code-behind:
conn.Open();
string insertQuery2 = "INSERT INTO UserData (username) values (#username)";
SqlCommand com2 = new SqlCommand(insertQuery2, conn);
com2.Parameters.AddWithValue("#username", HiddenFacebookID.Text);
com2.ExecuteNonQuery();
The Label content is really the facebook-ID, but the database gets NULL. Please Let me know if I wasn't clear.
I will appreciate any help, thanks!
The value you're setting in JavaScript isn't being posted back to the server. Only form values are posted to the server. And an asp:Label doesn't render as a form element.
Use a hidden form field instead:
<asp:Hidden ID="HiddenFacebookID" runat="server"></asp:Hidden>
And set its value in JavaScript:
document.getElementById('HiddenFacebookID').value = response.id;
Basically, regardless of the lies that WebForms has been telling for years, HTML content is not posted to the server when submitting a form :) Only form values are.
I am creating an ASP.net website using Visual Studio 2013. Specifically, I am trying to register a customer and insert the data in the customer table at the same time. When I register a customer, I also want to get the user id for that customer (which is inserted into my user accounts table in the database). So essentially I need to get the user id but also need to make sure that is the user id of the current user.
Here's what I tried to do:
String userQueryStr = "SELECT UserAccountID FROM UserAccounts WHERE Username = " + Email.Text;
System.Data.SqlClient.SqlCommand selectCommand = new System.Data.SqlClient.SqlCommand(userQueryStr, conn);
int userID = Convert.ToInt32(selectCommand.ExecuteScalar());
Email is the username btw. Essentially I am trying to make sure the Username field in the UserAccounts matches what is typed in the textbox on the registration page.
Then I tried to store an insert statement and also pass the userID int variable which is storing the Current user id from the User Account Table.
My problem is, after I run the application when I click the Registration button I get this error when I type the username test#testers.com:
An exception of type 'System.Data.SqlClient.SqlException' occurred in System.Data.dll but was not handled in user code
Additional information: The multi-part identifier "test#testers.com" could not be bound. The exception is thrown at this line:
int userID = Convert.ToInt32(selectCommand.ExecuteScalar());
Sql thinks your email is a field, because you don't have quotes before and after
String userQueryStr = "SELECT UserAccountID FROM UserAccounts WHERE Username = '" + Email.Text+"'";
Dear i want to search the user from database table when user was entered the value into search textbox by using LINQ in ADO.net
i have one search textbox ..when user enter any letter than search Username from table who's name contain this letter !
i have Code for this:-
[HttpPost]
public ActionResult Userlist(string UserName)
{
var U_master = db.User_Masters.ToList();
if (!string.IsNullOrEmpty(UserName))
U_master = U_master.Where(a => a.Username.Contains(UserName)).ToList();
return PartialView("Userlist", U_master);
}
By using this code i can search Username only Text box value will match with username of database table
but i want to display all the username record from database when user was the entered only single letter of Username ..and display all the Username who's name contain this letter .
please give format to write LIKE Query or give any example..!
You could use SqlMethods.Like(matchExpression,pattern)
var results = from c in db.costumers
where SqlMethods.Like(c.FullName, "%"+FirstName+"%,"+LastName)
select c;
The use of this method outside of LINQ to SQL will always throw a NotSupportedException exception.
Source: Taken from
Also take a look at this post
I want to do some action if button clicked for 3 times. Just like if users enters a wrong password for 3 times the page the page must be redirected to another page or something.
How to do action in ASP.NET C# if button clicked for 3rd time?
To check if a user has taken an action fox "x" times you need to store it somehwere. If you're using a relation database you could for example call a table LoginAttempts and there you store all unsuccesfull logins. When you have that table you can build your logic against it.
I'd use a session variable.
Another solution could be having a column in the users table named LoginAttempt(int)(default 0), how I would use that column is
Let's say you have a table in your databese called TblUsers with these columns
Id,
UserName,
Password,
LoginAttempt.
And let's say you have two TextBoxes on your Login.aspx page
TextBoxUserName,
TextBoxPassword.
Let's say you have one record in your TblUsers like this
Id : 1
UserName : rammstein
Password : ohnedich
LoginAttempt : 0
Now, you are in your Login.aspx.cs code
you have a method and in it you have
TblUsers user = new TblUsers();
And you have a bool login = false;.
You've got the username from TextBoxUserName.Text, you check if a user with this username exists then if it exist you do the below code.
Let's follow this scenerio
The given user tried to login with
UserName:rammstein
Password:duhast
Checked your database with username rammstein and found it, and took that record in your TblpUsers user then you checked whether user.Password and TextBoxPassword.Text matches.Well it won't match for the above example because
user.Password is ohnedich however TextBox.Password is duhast.This means the login is not successfull so you set false to your bool login.
Everything else belongs to the below code with if-else condition
if(user.LoginAttempt < 3){
if(!login)
{
user.LoginAttempt = user.LoginAttempt + 1;
}
else
{
user.LoginAttempt = 0;
}
}
else
{
//do something
}
Multiple solutions:
1) Session variable (Okay solution)
2) Static class variable (Not a good solution)
3) DB record field (Best solution)
4) Pass flag variable back and forth between view and controller (not a very good idea).
5) Browser cookie (can be cleared)