I have the following UPDATE command (written in VB) in my code.
Dim currentUser As String = User.Identity.Name
Dim myConnectionString As String = ConfigurationManager.ConnectionStrings("DBConnection").ConnectionString
Dim myCommand As New SqlCommand("UPDATE tblProfile SET Title= #Title, FirstName= #FirstName, LastName= #LastName, MiddleName= #MiddleName, HomePhoneNumber= #HomePhoneNumber, MobilePhoneNumber= #MobilePhoneNumber, Address= #Address, StreetName= #StreetName, StreetType= #StreetType, Suburb= #Suburb, PostCode= #PostCode, State= #State WHERE UserName = '" & currentUser & "'", New SqlConnection(myConnectionString))
myCommand.Connection.Open()
myCommand.Parameters.AddWithValue("#Title", Title.SelectedItem.Text)
myCommand.Parameters.AddWithValue("#FirstName", FirstName.Text)
myCommand.Parameters.AddWithValue("#LastName", LastName.Text)
If MiddleNames.Text = String.Empty Then
myCommand.Parameters.AddWithValue("#MiddleName", DBNull.Value)
Else
myCommand.Parameters.AddWithValue("#MiddleName", MiddleNames.Text)
End If
If HomePhoneNumber.Text = String.Empty Then
myCommand.Parameters.AddWithValue("#HomePhoneNumber", DBNull.Value)
Else
myCommand.Parameters.AddWithValue("#HomePhoneNumber", HomePhoneNumber.Text)
End If
If MobilePhoneNumber.Text = String.Empty Then
myCommand.Parameters.AddWithValue("#MobilePhoneNumber", DBNull.Value)
Else
myCommand.Parameters.AddWithValue("#MobilePhoneNumber", MobilePhoneNumber.Text)
End If
myCommand.Parameters.AddWithValue("#Address", AddressNumber.Text)
myCommand.Parameters.AddWithValue("#StreetName", StreetName.Text)
myCommand.Parameters.AddWithValue("#StreetType", StreetType.SelectedItem.Text)
myCommand.Parameters.AddWithValue("#Suburb", Suburb.Text)
myCommand.Parameters.AddWithValue("#PostCode", Postcode.Text)
myCommand.Parameters.AddWithValue("#State", State.SelectedItem.Text)
myCommand.ExecuteNonQuery()
myCommand.Connection.Close()
Dim myCommandPref As New SqlCommand("UPDATE tblPreferences SET Classical = #Classical, Comedy = #Comedy, Concerts = #Concerts, Dance = #Dance, DiningOut = #DiningOut, Exhibitions = #Exhibitions, Family = #Family, Festivals = #Festivals, Lifestyle = #Lifestyle, Musicals = #Musicals, Opera = #Opera, Rock = #Rock, Sports = #Sports, Theatre = #Theatre WHERE UserName = '" & currentUser & "'", New SqlConnection(myConnectionString))
myCommandPref.Connection.Open()
Dim boolClassical As Boolean = Preferences.Items(0).Selected
myCommandPref.Parameters.AddWithValue("#Classical", boolClassical.ToString)
Dim boolComedy As Boolean = Preferences1.Items(0).Selected
myCommandPref.Parameters.AddWithValue("#Comedy", boolComedy.ToString)
Dim boolConcerts As Boolean = Preferences.Items(1).Selected
myCommandPref.Parameters.AddWithValue("#Concerts", boolConcerts.ToString)
Dim boolDance As Boolean = Preferences1.Items(1).Selected
myCommandPref.Parameters.AddWithValue("#Dance", boolDance.ToString)
Dim boolDiningOut As Boolean = Preferences.Items(2).Selected
myCommandPref.Parameters.AddWithValue("#DiningOut", boolDiningOut.ToString)
Dim boolExhibitions As Boolean = Preferences1.Items(2).Selected
myCommandPref.Parameters.AddWithValue("#Exhibitions", boolExhibitions.ToString)
Dim boolFamily As Boolean = Preferences.Items(3).Selected
myCommandPref.Parameters.AddWithValue("#Family", boolFamily.ToString)
Dim boolFestivals As Boolean = Preferences1.Items(3).Selected
myCommandPref.Parameters.AddWithValue("#Festivals", boolFestivals.ToString)
Dim boolLifestyle As Boolean = Preferences.Items(4).Selected
myCommandPref.Parameters.AddWithValue("#Lifestyle", boolLifestyle.ToString)
Dim boolMusicals As Boolean = Preferences1.Items(4).Selected
myCommandPref.Parameters.AddWithValue("#Musicals", boolMusicals.ToString)
Dim boolOpera As Boolean = Preferences.Items(5).Selected
myCommandPref.Parameters.AddWithValue("#Opera", boolOpera.ToString)
Dim boolRock As Boolean = Preferences1.Items(5).Selected
myCommandPref.Parameters.AddWithValue("#Rock", boolRock.ToString)
Dim boolSports As Boolean = Preferences.Items(6).Selected
myCommandPref.Parameters.AddWithValue("#Sports", boolSports.ToString)
Dim boolTheatre As Boolean = Preferences1.Items(6).Selected
myCommandPref.Parameters.AddWithValue("#Theatre", boolTheatre.ToString)
myCommandPref.ExecuteNonQuery()
myCommandPref.Connection.Close()
When the user presses the button which fires that code, my page simply refreshes, but does not update the information in the database. I have looked around, and some people were saying you needed to have the primary key as the 'where' statement, so I made 'UserName' the primary key in both tables.
Could someone please help me to fix this.
I went back to my code after a few months today, and after a brief search through, found the problem... I needed to include 'if not IsPostBack then...' to my Page_Load. I was resetting my page each time the button was pressed, which reset the fields on my page, thus sending the same information back to my server - I was updating my server with the same information.
For anyone with the same problem, this helped me:
http://www.java-samples.com/showtutorial.php?tutorialid=1083
Related
I am working on a website with VB.NET and ASP.NET. I currently have recurring DropDownLists for the user to provide input.
The design is recurring. These DropDownLists get their values from a database table, Everything with the Web interface is working except for writing these recurring values to the database - that is just to give you some background.
I have set the ID's of each DropDownList like so:
FrequencyList.ID = String.Concat("FreqList", DBReader(0))
That is in a loop while reading the DatabaseReader.
This is what I'm having issues with (please note I simplified the code down to make it easier to read:
Dim i As Integer
DBCommand = New SqlCommand()
DBCommand.Connection = DBConnection
DBCommand.CommandType = Data.CommandType.StoredProcedure
DBCommand.CommandText = "StoredProcedureName"
DBConnection.Open()
For i = 1 To AspectTableLength
Dim ParamFrequencyID As SqlParameter = DBCommand.Parameters.Add("#nFrequencyID", SqlDbType.Int)
ParamFrequencyID.Value = FindControl("FreqList" & Convert.ToString(i))
ParamFrequencyID.Direction = ParameterDirection.Input
Next
The FindControl("FreqList" & Convert.ToString(i)) variable is incorrect because it does not access the value - and adding .SelectedItem.Value does not work.
I got help from a developer.
Dim MyControls As ControlCollection = Panel.Controls
Dim Number As Integer 'this is the same as "DBReader(0)"
For Each MyControl As Control In MyControls
If MyControl.ID Is Nothing Then
Else
If MyControl.ID.StartsWith("Span") Then
Number = Replace(MyControl.ID, "Span", "")
Dim Freq As DropDownList = PanelMain.FindControl(“FreqList” & Number)
Dim ParamFrequencyID As SqlParameter = DBCommand.Parameters.Add("#nFrequencyID", SqlDbType.Int)
ParamFrequencyID.Value = Freq.SelectedIndex
ParamFrequencyID.Direction = ParameterDirection.Input
DBCommand.ExecuteNonQuery()
DBCommand.Parameters.Clear()
End If
End If
Next
DBConnection.Close()
I have made a little custom log-in page in asp.net, see code:
Dim strCon As String = ConfigurationManager.ConnectionStrings("Goed").ConnectionString
'Create Connection String And SQL Statement
Dim strSelect As String = "SELECT COUNT(*) FROM tbl_LogIn WHERE Gebruiker = #Gebruiker AND Wachtwoord = #Wachtwoord"
Dim con As New SqlConnection(strCon)
Dim cmd As New SqlCommand()
cmd.Connection = con
cmd.CommandType = CommandType.Text
cmd.CommandText = strSelect
Dim Gebruiker As New SqlParameter("#Gebruiker", _
SqlDbType.VarChar)
Gebruiker.Value = TxtUs.Text.Trim().ToString()
cmd.Parameters.Add(Gebruiker)
Dim Wachtwoord As New SqlParameter("#Wachtwoord", _
SqlDbType.VarChar)
Wachtwoord.Value = TxtPw.Text.Trim().ToString()
cmd.Parameters.Add(Wachtwoord)
con.Open()
Dim result As Integer = DirectCast(cmd.ExecuteScalar(), Int32)
con.Close()
If result >= 1 Then
Response.Redirect("default.aspx")
Else
lblMsg.Text = "Gebruikers naam en of wachtwoord kloppen niet"
End If
End Sub
As you can see it directs to Default.aspx.
On my defaults.aspx page I have a header. In this header I want a small label to sdhow the logged in user something like: Hello [User] How can this be done?
Using Sessions:
While Directing to new page (at Login.aspx-in button's onClick event)
Session["valueName"]=value;
On new page( default.aspx in your case) use:
Label1.Text=Session["valueName"].ToString();
Or you can use cookies as well:
CREATE:
Response.Cookies("userInfo")("userName") = "DiederikEEn"
Response.Cookies("userInfo")("lastVisit") = DateTime.Now.ToString()
Response.Cookies("userInfo").Expires = DateTime.Now.AddDays(1)
READING:
If Not Request.Cookies("userName") Is Nothing Then
Label1.Text = Server.HtmlEncode(Request.Cookies("userName").Value)
End If
If Not Request.Cookies("userName") Is Nothing Then
Dim aCookie As HttpCookie = Request.Cookies("userName")
Label1.Text = Server.HtmlEncode(aCookie.Value)
End If
More here:
Cookies
Sessions
If you can create header in your master page then you can add Hello [User] there and call the session.
I'm writing a project and at the some point i have to check if there is an entry in database which matches the content of id-textbox and password-textbox. But I don't know how to indicate in my backend code(VB) that the query returns nothing.
This is the code I am using. But it doesn't work somehow. Error messages Are not being prompt:
Try
myconn.Open()
Dim stquery As String = "SELECT * from accountstbl WHERE user_ID = " & IdNumb.Text
Dim smd As MySqlCommand
Dim myreader As MySqlDataReader
smd = New MySqlCommand(stquery, myconn)
myreader = smd.ExecuteReader()
If myreader.Read() = True Then
If myreader.Item("user_ID") = IdNumb.Text Then
If myreader.Item("password") = CurrPass.Text Then
'some code if the user input is valid
Else
errorPassID.Visible = True
End If
Else
errorPassC.Visible = True
End If
End If
myconn.Close()
Catch ex As Exception
Dim ErrorMessage As String = "alert('" & ex.Message.ToString() & "');"
Page.ClientScript.RegisterStartupScript(Me.GetType(), "ErrorAlert", ErrorMessage, True) myconn.Close()
End Try
Will appreciate any help or suggestion.
I will try to check if the reader return rows and if not, emit an error message.
Also, do not use string concatenation to build queries, use always parametrized queries
myconn.Open()
Dim stquery As String = "SELECT * from accountstbl WHERE user_ID = #id"
Dim smd = New MySqlCommand(stquery, myconn)
smd.Parameters.AddWithValue("#id", Convert.ToInt32(IdNumb.Text))
Dim myreader = smd.ExecuteReader()
if Not myreader.HasRows Then
Dim ErrorMessage As String = "alert('No user found');"
Page.ClientScript.RegisterStartupScript(Me.GetType(), "ErrorAlert", ErrorMessage, True)
myconn.Close()
return
else
myreder.Read()
' no need to check if id is equal, you pass it as parameter to a where clause'
If myreader.Item("password") = CurrPass.Text Then
'some code if the user input is valid '
Else
errorPassID.Visible = True
' or error message '
End If
End If
myconn.Close()
Catch ex As Exception
Dim ErrorMessage As String = "alert('" & ex.Message.ToString() & "');"
Page.ClientScript.RegisterStartupScript(Me.GetType(), "ErrorAlert", ErrorMessage, True)
myconn.Close()
End Try
Note also that passing a clear text password along the wire is a serious security hole. I hope you have stored an hash of the password and check on that instead.
By the way, why don't pass also the password hash in the query? Somthing like this:
Dim stquery As String = "SELECT * from accountstbl WHERE user_ID = #id AND password = #pwd"
In this way, if you have a record returned the user is validated and your client side code will be simple
I have a web page with following fields
name,address,post
with three textboxes.I want to provide the search facility to the user.if user enter only the name and hit search it should search only by name, if user enter the values for all the textboxes it should query the database with all 3 values.like wise how can i write the sql query for all the searching possibilities?
select *
from Table1
where
(coalesce(#Name, '') = '' or Name = #Name) and
(coalesce(#Address, '') = '' or Address = #Address) and
(coalesce(#Post, '') = '' or Post = #Post)
I prefer this option for the query. If the user enters a value in only one of the fields, then pass a null to the parameter of the other respective fields.
Create PROCEDURE [dbo].[uspGetPeople]
#name varchar(50),
#Address varchar(200),
#Post varchar(5)
AS
SET NOCOUNT ON;
Select name, address, post
from tblPeople
where (name = #Name or #Name IS NULL) and
(address = #Address or #Address IS NULL) and
(post = #Post or #Post IS NULL)
A simple VB.NET example to call the stored procedure:
Dim strName As String = NameTextBox.Value
Dim strAddress as string = AddressTextBox.Value
Dim strPost as string = PostTextBox.Value
Dim strSQL As String = "uspGetPeople"
Dim strConn As String = "My.Database.ConnectionString"
Dim cn As New SqlConnection(strConn)
Dim cmd As New SqlCommand(strSQL, cn)
cmd.CommandType = CommandType.StoredProcedure
If not string.isnullorempty(strName) then
cmd.Parameters.AddWithValue("#Name", strName)
Else
cmd.Parameters.AddWithValue("#Name", dbnull.value)
End if
If not string.isnullorempty(strPost) then
cmd.Parameters.AddWithValue("#Post", strPost)
Else
cmd.Parameters.AddWithValue("#Post", dbnull.value)
End if
If not string.isnullorempty(strAddress) then
cmd.Parameters.AddWithValue("#Address", strAddress)
Else
cmd.Parameters.AddWithValue("#Address", dbnull.value)
End if
Dim dr As SqlDataReader
Using cn
cn.Open()
dr = cmd.ExecuteReader
While dr.Read
'process records returned
'dr("name")
'dr("address")
'dr("post")
End While
cn.Close()
End Using
I currently have a problem attepting to update a record within my database. I have a webpage that displays in text boxes a users details, these details are taken from the session upon login. The aim is to update the details when the user overwrites the current text in the text boxes.
I have a function that runs when the user clicks the 'Save Details' button and it appears to work, as i have tested for number of rows affected and it outputs 1. However, when checking the database, the record has not been updated and I am unsure as to why.
I've have checked the SQL statement that is being processed by displaying it as a label and it looks as so:
UPDATE [users]
SET [email] = #email,
[firstname] = #firstname,
[lastname] = #lastname,
[promo] = #promo
WHERE [users].[user_id] = 16
The function and other relevant code is:
Sub Page_Load(sender As Object, e As EventArgs)
usernameLabel.text = session.contents.item("UserName")
if usernameLabel.text = "" then
logoutButton.Visible = False
loggedInAsLabel.Visible = False
else
labelGuest.Visible = False
linkLogin.Visible = False
linkRegister.Visible = False
end if
emailBox.text = session.contents.item("Email")
firstBox.text = session.contents.item("FirstName")
lastBox.text = session.contents.item("LastName")
promoBox.text = session.contents.item("Promo")
End Sub
Sub Button1_Click(sender As Object, e As EventArgs)
changeDetails(emailBox.text, firstBox.text, lastBox.text, promoBox.text)
End Sub
Function changeDetails(ByVal email As String, ByVal firstname As String, ByVal lastname As String, ByVal promo As String) As Integer
Dim connectionString As String = "Provider=Microsoft.Jet.OLEDB.4.0; Ole DB Services=-4; Data Source=C:\Documents an"& _
"d Settings\Paul Jarratt\My Documents\ticketoffice\datab\ticketoffice.mdb"
Dim dbConnection As System.Data.IDbConnection = New System.Data.OleDb.OleDbConnection(connectionString)
Dim queryString As String = "UPDATE [users] SET [email]=#email, [firstname]=#firstname, [lastname]=#lastname, "& _
"[promo]=#promo WHERE ([users].[user_id] = " + session.contents.item("ID") + ")"
Dim dbCommand As System.Data.IDbCommand = New System.Data.OleDb.OleDbCommand
dbCommand.CommandText = queryString
dbCommand.Connection = dbConnection
Dim dbParam_email As System.Data.IDataParameter = New System.Data.OleDb.OleDbParameter
dbParam_email.ParameterName = "#email"
dbParam_email.Value = email
dbParam_email.DbType = System.Data.DbType.[String]
dbCommand.Parameters.Add(dbParam_email)
Dim dbParam_firstname As System.Data.IDataParameter = New System.Data.OleDb.OleDbParameter
dbParam_firstname.ParameterName = "#firstname"
dbParam_firstname.Value = firstname
dbParam_firstname.DbType = System.Data.DbType.[String]
dbCommand.Parameters.Add(dbParam_firstname)
Dim dbParam_lastname As System.Data.IDataParameter = New System.Data.OleDb.OleDbParameter
dbParam_lastname.ParameterName = "#lastname"
dbParam_lastname.Value = lastname
dbParam_lastname.DbType = System.Data.DbType.[String]
dbCommand.Parameters.Add(dbParam_lastname)
Dim dbParam_promo As System.Data.IDataParameter = New System.Data.OleDb.OleDbParameter
dbParam_promo.ParameterName = "#promo"
dbParam_promo.Value = promo
dbParam_promo.DbType = System.Data.DbType.[String]
dbCommand.Parameters.Add(dbParam_promo)
Dim rowsAffected As Integer = 0
dbConnection.Open
Try
rowsAffected = dbCommand.ExecuteNonQuery
Finally
dbConnection.Close
End Try
labelTest.text = rowsAffected.ToString()
if rowsAffected = 1 then
labelSuccess.text = "* Your details have been updated and saved"
else
labelError.text = "* Your details could not be updated"
end if
End Function
Any help would be greatly appreciated.
Does your page have a RequiresTransaction property? If so, check that there are no exceptions thrown elsewhere during the request which might cause the transaction to roll back - leaving the data unchanged.
Are you sure that you're updating the database you think you're updating? I don't like the look of that connection string at all (and, frankly, I doubt Paul Jarratt would be too happy to see it posted here).