Update Only one field in MS SQL Using Classic ASP - sql-server

I have been banging my head with this script and need to assistance. I am trying to create a registration form that connects to the following sql fields: Acct_ID, Username, Password, FirstName, LastName, Confirmation, RegistrationDate and AccountNum.
What I have been able to do so far is get the form inserted into the database and have a cdosys email sent out to the email address(username) with a querystring attached to a link embedded in the email. The querystring is the AccountNum field from the registration form.
What I want to try to do is update the confirmation field only in the database when the user clicks on the link which looks like this:
http://www.domainname.com/Presenter_Account_Confirm_Registration.asp?AccountNum=2152012319101300766363428210152260.
I verified that the Account Number is transferred to the confirmation page, but I am stumped as to how to update just the confirmation field in the database. Any help would be greatly appreciated. Thank you!

Making some assumptions here, that Acct_ID is an INT, is the same as AccountNum, and that you want to set Confirmation to 1:
<%
Acct_ID = Request.QueryString("AccountNum")
set cmd = CreateObject("ADODB.Command")
cmd.ActiveConnection = conn ' assume ADODB.Connection has been set up
cmd.CommandType = adCmdText
sql = "UPDATE dbo.tablename SET Confirmation = 1 WHERE Acct_ID = ?"
cmd.Parameters(0).value = Acct_ID
cmd.CommandText = sql
cmd.Execute
%>

Related

MS Access - SQL Server Login Prompt won't go away

So I have this application and I moved all local tables to SQL Server using upsizing, now they are currently linked tables. I'm able to access tables and forms related to tables can be accessed with no problems. But when I programmatically fetch a record, or perform a sql operation in VBA script, a SQL Server Login prompt pops up asking me to enter in the SQL Authentication login to access the database.
I followed this link here:
https://support.microsoft.com/en-us/kb/177594
Where this is my end code:
Dim db1 As Database
Dim db2 As Database
Dim rs As Recordset
Dim strConnect As String
Set db1 = OpenDatabase("C:\Workspace\ms1.mdb")
strConnect = UCase(db1.TableDefs("dbo_TableA").Connect) & ";UID=User1;PWD=Password1"
Set db2 = OpenDatabase("", False, False, strConnect)
db2.Close
Set db2 = Nothing
Set rs = db1.OpenRecordset("dbo_TableA")
rs.Close
db1.Close
Set rs = Nothing
Set db1 = Nothing
DoCmd.RunCommand acCmdSaveRecord
'Sql Server login prompt pops up after running the below code;'
If DCount("*", "TableA", "[ColA] = [forms]![FRM_LOGS]![USER]") = 0 Then
MsgBox "User ID not found - contact HelpDesk", vbCritical
DoCmd.Quit
Exit Sub
End If
The DCount is triggering the SQL Server Login Prompt. I need this prompt to go away. If I open up a form, query, report, anything where the access object is bound to the data, I get no message. It ONLY happens in VBA when I'm trying to access the data object.
Edit! I did find the culprit. I deleted the linked table to the TableA in sql server, and I relinked it again, and clicked the Save password checkbox. I did this before, and it didn't work. Did it again, and it fixed everything. Not sure why this didn't work the first time. I marked the below as an answer because that did solve the problem given the circumstances.
Not sure what you're doing here with two database connections and using DCOUNT on an internal table?
It looks like your database connection has linked tables that have stored passwords
Why not just use your recordset that works to check for a valid user?
Set db1 = OpenDatabase("C:\Workspace\ms1.mdb")
Set rs = db1.OpenRecordset("SELECT [ColA] FROM [dbo_TableA] WHERE [ColA] = """ & [forms]![FRM_LOGS]![USER] & """")
if rs.EOF Then
MsgBox "User ID not found - contact HelpDesk", vbCritical
DoCmd.Quit
Exit Sub
End If
rs.Close
db1.Close
Set rs = Nothing
Set db1 = Nothing

Possible for TSQL query to use a value from a Access Forms?

I am working on an Access DB, which have ODBC linked SQL Server table, and I have following script to run TSQL query, as you can see I tried to include a value from Access Forms in the query, but it fails to run. The form is opened and filled with data when I execute the script. I am wondering if this is impossible or there is another way of doing it? I am new to TSQL and SQL server, here is my question. Appreicate if someone can help. Thanks a lot.
Function formtest()
Dim qryd As QueryDef
Set qryd = CurrentDb.CreateQueryDef("")
qryd.Connect = "ODBC;DSN=SQLSERVER;"
qryd.SQL = "UPDATE dbo.table1 SET firstname = [Forms]![testform]![datainput]"
qryd.ReturnsRecords = False
qryd.Execute
End Function
The SQL Server doesn't know anything about your forms. You have to send the data with the query. Something like this:
qryd.SQL = "UPDATE dbo.table1 SET firstname = '" & [Forms]![testform]![datainput] & "'"
One thing you have to be aware of though is that if there are any single quotes in your datainput it could invalidate the SQL. It could also be a security issue. Either test for single quotes and raise an error, or replace each of them with two.
The best way to do it is to use a parameterized query. This will absolutely prevent issues SQL injection and also help with performance in many cases. Unfortunately, I don't believe you can create a paramaterized query for SQL Server using DAO. You would have to convert to ADO, which is best suited for sending queries to a SQL Engine other than Jet.
To use ADO you might have to add a reference to Microsoft ActiveX Data Objects by opening the VBA code window and selecting Tools -> References -> and checking the box next to it. Then your code would look something like this:
Dim Conn1 As ADODB.Connection
Dim Cmd1 As ADODB.Command
Dim Param1 As ADODB.Parameter
Rem Create and Open Connection Object.
Set Conn1 = New ADODB.Connection
Conn1.ConnectionString = "ODBC;DSN=SQLSERVER;"
Conn1.Open
Rem Create Command Object.
Set Cmd1 = New ADODB.Command
Cmd1.ActiveConnection = Conn1
Cmd1.CommandText = "UPDATE dbo.table1 SET firstname = ?"
Rem Create Parameter Object.
Set Param1 = Cmd1.CreateParameter(, adVarChar, adParamInput, 25)
Param1.Value = [Forms]![testform]![datainput]
Cmd1.Parameters.Append Param1
Set Param1 = Nothing
Rem Open Recordset Object.
Call Cmd1.Execute

Verify credentials from database

I had confusion with my code:
Dim sqladapter As SqlDataAdapter = New SqlDataAdapter()
Dim sqlcmd As SqlCommand = New SqlCommand()
sqlcmd = New SqlCommand("SELECT login, pass from Table1 where login=" & login.Text & "and pass='" & password.Text.ToString() & "';", connect)
Dim dr As SqlDataReader = sqlcmd.ExecuteReader()
Dim dt As DataTable = New DataTable()
dt.Load(dr)
If (dt.Rows.Count = 1) Then
'Display welcome page or do some action here.
Now, my question is, is there any other way of doing Rows.Count==1 . I'm feeling that it is very wrong and makes no sense at.
How do you verify from database that a user has only one valid record in table other than counting rows.
Thanks in Advance :)
(Please ask me before reporting question)
You have two problems, one is called Sql Injection and you have already numerous links that explain why is really bad. Another one is the plain text password stored in your database. This is a big security concern because everyone that has the possibility to look at your database could see the passwords of your users. (The gravity of this, of course, is linked to the nature of your application but cannot be downplayed) See this link for an answer on how to hash a string (a password) and get its encrypted version to store in the database instead of the plain text.
Finally the code you use could be changed to avoid both the SqlDataAdapter and the DataTable.
Just use an ExecuteScalar against an IF EXIST query that return just 1 if the user/password exists or zero if not
Dim cmdText = "IF EXISTS(SELECT 1 FROM Table1 WHERE login = #log AND pass = #pwd) " & _
"SELECT 1 ELSE SELECT 0"
using connect = new SqlConnection(connectionstring)
using sqlcmd = New SqlCommand(cmdText, connect)
connect.Open()
sqlcmd.Parameters.AddWithValue("#log", login.Text)
sqlcmd.Parameters.AddWithValue("#pwd", password.Text) ' <- Subst with a call to an hash function
Dim exists = Convert.ToInt32(sqlcmd.ExecuteScalar())
if exists = 1 Then
'Display welcome page or do some action
else
end if
End Using
End Using
There is only one way to answer to the question and its to count rows. The different solution would be to count them in database. For example you could write stored procedure that takes username and password and returns boolean this way you would drag less data.
As a side note there is potential sql injection in your code. You should not store clear password in database. You should return the whole row and match hash of the password from database to the hash of the paasword that you get from UI.

Update a password if user name and old password match

This is the first time I run any type of queries and/or connect to a database through vb. I have looked up my problem on line but have not found exactly what I am looking for.
I have a simple login page on my windows application that runs out of a compact .sdf database. I need to add a procedure that allows the user to change the password.
If the user name in textbox1 and the password in textbox2 match what I have stored in my database, then replace the password with the values of textbox3.
So far I have been able to figure out how to create a new account and verify the log in. I log in using the following:
SELECT username, userpassword
FROM UserInfo
WHERE (username LIKE #username) AND (userpassword LIKE #userpassword)
Then the procedure on my button:
' Check if username or password is empty
If txtPassword.Text = "" Or txtUserName.Text = "" Then
MessageBox.Show("Please complete the required fields..", "Authentication Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
'Clear all fields
txtPassword.Text = ""
txtUserName.Text = ""
'Focus on Username field
txtUserName.Focus()
Else
'If the password and username match, open the main form.
If Not UserInfoTableAdapter1.Login(txtUserName.Text, txtPassword.Text) = Nothing Then
Dim frmWelcome As New frmWelcomePage
frmWelcome.Show()
Me.Hide()
Else
MessageBox.Show("You have entered an invalid user name or password", "Invalid Login", MessageBoxButtons.OK, MessageBoxIcon.Error)
'Clear all fields
txtPassword.Text = ""
txtUserName.Text = ""
'Focus on Username field
txtUserName.Focus()
End If
End If
How can I use something similar to change the password?
As #pickypg said you should definitely look for an exact match with passwords and usernames. Also you should consider a one way hash for user passwords. This answer does a good job of describing the potential danger of storing plain text passwords. This article has related information and is also amusing.
That aside the sql you're looking for might be something like this:
create procedure updateUserPassword
#userName varchar(max)
,#oldHashedPassword nvarchar(128)
,#newHashedPassword nvarchar(128)
as
begin
set nocount on;
if exists ( select 1 from UserInfo where username = #userName and userpassword = #oldHashedPassword )
begin
update UserInfo set userPassword = #newHashedPassword where username = #userName;
end
else
begin
raiserror('No record found for user', 16, 1);
end
end

Retrieving data from ListView control in VB.NET

I have a ListView setup in details mode that looks like this:
When the user presses the delete button, I need to go ahead and delete their record from the database. This I can do fine, but I'm stuck on how I retrieve the data that is highlighted in the ListView control. I've tried using Google but all the examples I found have failed to work.
Can someone help me out here?
You should be able to get the underlying object by using:
ListView1.SelectedItems(0)
Once you remove it from the database you should rebind the data.
Dim name, room, subject, date, period As String
If listviewName.SelectedItems.Count > 0 then
'*********** transfer selected data on declare String variable ************'
name= listviewName.SelectedItems(0).SubItems(0).Text
room = listviewName.SelectedItems(0).SubItems(1).Text
subject = listviewName.SelectedItems(0).SubItems(2).Text
date= listviewName.SelectedItems(0).SubItems(3).Text
period= listviewName.SelectedItems(0).SubItems(4).Text
'*********** delete **************'
cmd1.Connection = MYSQLCON
MYSQLCON.Open()
cmd1.CommandText = "DELETE FROM tablename WHERE columnname = '" & name & "'"
reader = cmd1.ExecuteReader
MYSQLCON.Close()
End If

Resources