Validate if username already exists - mysql

In the form that I create new users, I would like it to validate if the username already existed or not, then in the register button I put the following code:
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Try
Dim Inserir As String = "INSERT INTO `techstorehunter`.`utilizadores`(`Username`,`Password`,`pergunta`,'resperg')VALUES('" & TextBox1.Text & "','" & TextBox2.Text & "','" & TextBox3.Text & "','" & ComboBox1.Text & "')"
ExecuteQuery(Inserir)
Catch
MessageBox.Show("Username already exists")
End Try
If TextBox1.Text = "" Then
MessageBox.Show("Insert a username")
End If
If TextBox2.Text = "" Then
MessageBox.Show("Insert a password")
End If
If TextBox3.Text = "" Then
MessageBox.Show("You need to answer a question")
End If
If ComboBox1.Text = "" Then
MessageBox.Show("You need to select a question")
End If
End Sub
But everytime I create a user it says that it already exists, even if not, what i can do? Thanks.
PS : "Inserir" means "Insert" but my language is Portuguese.

There are several issues with your code :
First, you validate the input after running the sql query : you should validate first, and if everything goes well then do the INSERT, otherwise you are exposing to either inserting dumb data to database, or getting the « User already exists » warning on incomplete input
Also, you catch all database errors and interpret them as « User already exists » ; by proceeding this way you are potentially hiding other database errors than duplicate user record. The proper way to proceed is to :
after form validation, check for per-existing user with a query like follows, where the question mark should be replaced by the submitted user name. If the query returns anything, then you know that you have a duplicated user for sure, and you can raise the appropriate warning and stop the processing.
SELECT 1 FROM `techstorehunter`.`utilizadores` WHERE `Username` = ?
if the first query returns nothing, you can run the INSERT statement
everytime your run a query, you want to catch errors, report them with the full error message, and abort the processing

Related

Unwanted Scientific Notation in MS Access

I'm encountering a very strange problem with MS Access. I have some VBA code used on a password reset form. The code hashes the input password and then saves the hash to a table of users. Here's a relevant snippit:
If newPW1 = newPW2 Then
MsgBox ("Passwords Match!")
hashPW = Encrypt(newPW1)
MsgBox ("HashedPW is " & hashPW)
updatePW = "UPDATE Users SET Password = " & hashPW & " WHERE Username = pwChangeUsrnm"
DoCmd.RunSQL (updatePW)
the MSGboxes are my debugging notes. I know the hash generates properly as a long string of numbers, all well and good. When I go into the datasheet for the Users table though, the number has always been converted into scientific notation.
Here's a screenshot of the data sheet. bob.smith is an example of what I end up with after the code runs, the other two are gibberish I entered manually. The field is formatted as a string, so I'm not sure why it would even try to convert the number into SN when as far as I can tell the item is always a string.
I'm thinking the error must creep in around the SQL query? If there's a better way of doing this then I'm all ears.
Thanks in advance for your help!
datasheet
design view
Complete code, just in case:
Option Compare Database
Private Sub Command84_Click()
Dim hashPW As String
Dim updatePW As String
Dim checkName As String
checkName = Nz(DLookup("Username", "Users", "Username = pwChangeUsrnm"), "aaa")
MsgBox ("checkName set to " & checkName)
If pwChangeUsrnm = checkName Then
MsgBox ("Username Found")
If newPW1 = newPW2 Then
MsgBox ("Passwords Match!")
hashPW = Encrypt(newPW1)
MsgBox ("HashedPW is " & hashPW)
updatePW = "UPDATE Users SET Password = " & hashPW & " WHERE Username = pwChangeUsrnm"
DoCmd.RunSQL (updatePW)
Else
MsgBox ("Passwords Do Not Match!")
End If
Else
MsgBox ("Username not found")
End If
End Sub
I think Andre has the right of it. I tried adjusting the hashing code to add a letter character and this worked, but then I needed to go back and add the single quote around the hashed PW value- which probably would have made the code work even without adding the letter:
If newPW1 = newPW2 Then
MsgBox ("Passwords Match!")
hashPW = Encrypt(newPW1)
MsgBox ("HashedPW is " & hashPW)
updatePW = "UPDATE Users SET Password = '" & hashPW & "' WHERE Username = pwChangeUsrnm"
DoCmd.RunSQL (updatePW)
A thanks to Zaph's second comment on security as well, I'll take that all into account. For the purposes of this database security isn't too much of a concern as it will be sitting behind existing security measures. The hashing of passwords is more just to avoid ever displaying the passwords in plain text. Nevertheless it's useful to know about these extra functions.

MS Access Code issue for Reminders

I'm trying to setup reminders based on tasks added from a Table called "Tasks" Here is the code I'm using but something isn't right as it keeps giving me issues with the following line:
intStore = DCount("[TaskName]", "[Status]", "[DueDate] <=Now() AND [Complete] =0")
When the code runs I get the error:
Microsoft Access database engine cannot find the input table or query
for 'Status' Make sure it exists and is spelled correctly.
In my table I have fields for Task Name, Status, and Due Date so I'm not exactly sure why this is coming up.
Below is the entire line of code:
Private Sub Form_Load()
'On Load of the switchboard check Jobs table for any uncompleted jobs
Dim intStore As Integer
intStore = DCount("[Priority]", "[Tasks]", "[DueDate] <=Now() AND [PercentComplete] <=0")
If intStore = 0 Then
Exit Sub
Else
If MsgBox("There are " & intStore & " uncompleted jobs" & _
vbCrLf & vbCrLf & "Would you like to see these now?", _
vbYesNo, "You Have Uncomplete Jobs...") = vbYes Then
DoCmd.Minimize
DoCmd.OpenForm "Tasks", acNormal
Else
Exit Sub
End If
End If
End Sub
You can only perform a DCount on one field (primary key is best if you are just doing a general count on the table). You have entered "[Status]" where Access is expecting a table or query name to be used as the source of the [TaskName] field.
See here for more information.
Judging by your other code example I expect that your code needs to be:
intStore = DCount("[TaskName]", "[Tasks]", "[DueDate] <=Now() AND [Complete] =0")

Setting and moving to a bookmark

I have an error message on a form that checks for an existing SSN on the BeforeUpdate event of a text box. If it already exists in the database, the user is given a message box to this effect, and has the option to go to the existing record. I'm using this example code here. My code is below.
Private Sub txtSocialSecurityNumber_BeforeUpdate(Cancel As Integer)
'check for existing SSN
Dim SSN As String
Dim strLinkCriteria As String
Dim rsc As Recordset
Set rsc = Me.RecordsetClone
SSN = Me.txtSocialSecurityNumber.Value
strLinkCriteria = "[SocialSecurityNumber] = " & "'" & SSN & "'"
'look for duplicates
If DCount("SocialSecurityNumber", "Person", LinkCriteria) > 0 Then
'Undo duplicate entry
Me.Undo
'error message
intResponse = MsgBox("Social Security Number " & SSN & " already exists in database." & _
vbCrLf & vbCrLf & "Would you like to view the record?", vbYesNo, "Duplicate SSN")
If intResponse = vbYes Then
'go to record
rsc.FindFirst strLinkCriteria
Me.Bookmark = rsc.Bookmark
ElseIf intResponse = vbNo Then
Exit Sub
End If
End If
Set rsc = Nothing
End Sub
According to this code, and several other examples I have looked up, it seems like I'm doing everything right, but I must not be because when I try to run the code and go to the existing record, I get the error "Run-time error '424': Object Required". When I debug, the row rst.FindFirst strLinkCriteria is highlighted, and hovering over it gives me the text strLinkCriteria = "[SocialSecurityNumber] = '123456789'" (123456789 is a known sample SSN in my database). Thank you to Sergey S. for pointing out the spelling error that fixed this section.
When I tell the message box to go to the record with the existing SSN, it gives me Run-time error '3021': No current record. Debug highlights the line Me.Bookmark = rsc.Bookmark with the message rsc.Bookmark = <No current record.>. So it sounds like I'm not assigning the bookmark correctly.
I've never used bookmarks before, so I'm not really sure what I'm doing wrong here. Any help would be appreciated.
You declared rsc, but used rst.
Change your code to
rsc.FindFirst strLinkCriteria
And I'd recommend always use Option Explicit in every module (default can be changed on options), otherwise you'll face with such kind strange errors. With this option the typo would be found by compiller, not at runtime.

Why is my DLOOKUP returning only a partially correct record?

Alright. This is my first post ever so I'll try to be as detailed as I can. I have a Person_AfterUpdate() event on a Form named frm_Contact_Info, that is supposed to check a table, named "tbl_Contact_Info," for an existing record. If the record exists, then a message pops up stating that the record already exists, and to check the name. Then it asks if I am creating a new record with the existing name, or if the record that is returned is the same person. The problem I am having is that the DLookup shows the correct name, but does not return the correct phone number or address to my form.
Here is my code. I'm not super skilled at programming, but I tried to make it as understandable as possible. If you want screen shots, let me know. This is the first time I've actually tried to build a database, and I know my skills are not as great as some of yours. I've tried to research as much as I could to find the answer to this, but everything I've tried so far brings me back to this problem where the DLOOKUP is returning the correct NewPerson, but not the correct phone number or e-mail address. Please help!
Private Sub Person_AfterUpdate()
Dim NewPerson As String
Dim stLinkCriteria As String
Dim PersID As Integer
On Error GoTo E:
NewPerson = Me.Person.Value
stLinkCriteria = "[Person] = " & "'" & NewPerson & "'"
If Me.Person = DLookup("[Person]", "tbl_Contact_Info", stLinkCriteria) Then
MsgBox "The name, " & NewPerson & ", has already been added to the database." _
& vbCr & vbCr & "Please check the name and try again.", vbInformation, "Duplicate Information"
Me.Undo
End If
PersID = DLookup("[ID]", "tbl_Contact_Info", stLinkCriteria)
Me.DataEntry = False
DoCmd.FindRecord PersID, , , , , acCurrent
Response = MsgBox("Are you adding a new record with the same name?", vbYesNo, "New or Existing Record")
If Response = vbYes Then
DoCmd.GoToRecord , "", acNewRec, 1
Me!Person.Value = NewPerson
Else
Me.DataEntry = True
DoCmd.GoToRecord , "", acNewRec, 1
End If
Exit Sub
E:
Me!Person.Value = NewPerson
End Sub`
Perhaps you have multiple records with the same value in the attribute you are using as your lookup value?

How can I check for null values in Access?

I am new to Access. I have a table full of records. I want to write a function to check if any id is null or empty. If so, I want to update it with xxxxx.
The check for id must be run through all tables in a database.
Can anyone provide some sample code?
I'm not sure if you are going to be able to find all tables in the database with Access SQL. Instead, you might want to write up some VBA to loop through the tables and generate some SQL for each table. Something along the lines of:
update TABLE set FIELD = 'xxxxxx' where ID is null
Check out the Nz() function. It leaves fields unaltered unless they're null, when it replaces them by whatever you specify.
For reasonable numbers and sizes of tables, it can be quicker to just
open them
sort by each field in turn
inspect for null values and replace manually
It's good practice to find out where the nulls are coming from and stop them - give fields default values, use Nz() on inputs. And have your code handle any nulls that slip through the net.
I'm calling it the UpdateFieldWhereNull Function, and shown is a Subroutine which calls it (adapted from http://www.aislebyaisle.com/access/vba_backend_code.htm)
It updates all tables in the DbPath parameter (not tested, handle with care):
Function UpdateFieldWhereNull(DbPath As String, fieldName as String, newFieldValue as String) As Boolean
'This links to all the tables that reside in DbPath,
' whether or not they already reside in this database.
'This works when linking to an Access .mdb file, not to ODBC.
'This keeps the same table name on the front end as on the back end.
Dim rs As Recordset
On Error Resume Next
'get tables in back end database
Set rs = CurrentDb.OpenRecordset("SELECT Name " & _
"FROM MSysObjects IN '" & DbPath & "' " & _
"WHERE Type=1 AND Flags=0")
If Err <> 0 Then Exit Function
'update field in tables
While Not rs.EOF
If DbPath <> Nz(DLookup("Database", "MSysObjects", "Name='" & rs!Name & "' And Type=6")) Then
'UPDATE the field with new value if null
DoCmd.RunSQL "UPDATE " & acTable & " SET [" & fieldName & "] = '" & newFieldValue & "' WHERE [" & fieldName & "] IS NULL"
End If
rs.MoveNext
Wend
rs.Close
UpdateFieldWhereNull = True
End Function
Sub CallUpdateFieldWhereNull()
Dim Result As Boolean
'Sample call:
Result = UpdateFieldWhereNull("C:\Program Files\Microsoft Office\Office\Samples\Northwind.mdb", "ID", "xxxxxx")
Debug.Print Result
End Sub