my sql table is not updated, when i do???!!, the codes are as folow:
C#
string connectionStringid = ConfigurationManager.ConnectionStrings["CustomerDB"].ConnectionString;
connad = new SqlConnection(connectionStringad);
commandad = new SqlCommand("", connad);which are class variables. the folowing codes for insert and update, insert works, but not update???!!:
C#
public static string AddAd(Customerad customerad, int Id)
{
string result;
string q = string.Format("select * from customerad1 where Email='{0}' and Title='{1}'", customerad.Email, customerad.Title);
try
{
connad.Open();
commandad.CommandText = q;
int amountOfUsers = Convert.ToInt32(commandad.ExecuteScalar());
if (amountOfUsers < 1) //new user
{
commandad.CommandText = @"INSERT INTO customerad1 (Name, Email, Phone, Country, ZipCode, Category, Title, Price, Images, Date_Time, Description, Bussiness, Payment) VALUES
('" + customerad.Name + "','" + customerad.Email + "','" + customerad.Phone + "','" + customerad.Country + "','" + customerad.ZipCode + "','" + customerad.Category + "','" + customerad.Title + "','" + customerad.Price + "','" + customerad.Images + "','" + customerad.Date_Time + "','" + customerad.Description + "','" + customerad.Bussiness + "','" + customerad.Payment + "')";
commandad.ExecuteNonQuery();
result = "Ad registered!";
}
else //user exist
{
commandad.CommandText = @"UPDATE customerad1 SET ([Name]='" + customerad.Name + "', [Email]='" + customerad.Email + "', " +
"[Phone]='" + customerad.Phone + "', " +
"[Country]='" + customerad.Country + "', [ZipCode]='" + customerad.ZipCode + "', [Category]='" + customerad.Category + "', " +
"[Title]='" + customerad.Title + "', [Price]='" + customerad.Price + "', [Images]='" + customerad.Images + "', " +
"[Date_Time]='" + customerad.Date_Time + "', [Description]='" + customerad.Description + "', [Bussiness]='" + customerad.Bussiness + "', [Payment]='" + customerad.Payment + "') where [Id]='" + Id + "' ";
commandad.ExecuteNonQuery();
result = "Ad updated!";
}
}
}i cannot find the problem... please help me, i appreciate... kind regards

Jaimin ShethiyaRank #177 · 13.7K reputationPosted Nov 3, 2023, 8:48 AM EDT
Hello Venus
Please update the below mention code and verify it.
commandad.CommandText = @"UPDATE customerad1 SET [Name]='" + customerad.Name + "', [Email]='" + customerad.Email + "', " +
"[Phone]='" + customerad.Phone + "', " +
"[Country]='" + customerad.Country + "', [ZipCode]='" + customerad.ZipCode + "', [Category]='" + customerad.Category + "', " +
"[Title]='" + customerad.Title + "', [Price]='" + customerad.Price + "', [Images]='" + customerad.Images + "', " +
"[Date_Time]='" + customerad.Date_Time + "', [Description]='" + customerad.Description + "', [Bussiness]='" + customerad.Bussiness + "', [Payment]='" + customerad.Payment + "' where [Id]='" + Id + "' ";
Amit MohantyRank #112 · 20K reputationPosted Nov 3, 2023, 8:50 AM EDT
Firstly your code is vulnerable to SQL injection. You should use parameterized queries instead of directly embedding values into your SQL statements. This will also make your code more secure and also consider using the
usingstatement for your SqlConnection and SqlCommand objects to ensure they are properly disposed of after use Check this:public static string UpdateAd(Customerad customerad, int Id) { string result; string q = "SELECT COUNT(*) FROM customerad1 WHERE Email = @Email AND Title = @Title"; try { using (SqlConnection connad = new SqlConnection(ConfigurationManager.ConnectionStrings["CustomerDB"].ConnectionString)) { connad.Open(); using (SqlCommand commandad = new SqlCommand(q, connad)) { commandad.Parameters.AddWithValue("@Email", customerad.Email); commandad.Parameters.AddWithValue("@Title", customerad.Title); int amountOfUsers = Convert.ToInt32(commandad.ExecuteScalar()); if (amountOfUsers < 1) // New user { string insertQuery = @"INSERT INTO customerad1 (Name, Email, Phone, Country, ZipCode, Category, Title, Price, Images, Date_Time, Description, Bussiness, Payment) VALUES (@Name, @Email, @Phone, @Country, @ZipCode, @Category, @Title, @Price, @Images, @Date_Time, @Description, @Bussiness, @Payment)"; using (SqlCommand insertCommand = new SqlCommand(insertQuery, connad)) { insertCommand.Parameters.AddWithValue("@Name", customerad.Name); insertCommand.Parameters.AddWithValue("@Email", customerad.Email); insertCommand.Parameters.AddWithValue("@Phone", customerad.Phone); insertCommand.Parameters.AddWithValue("@Country", customerad.Country); insertCommand.Parameters.AddWithValue("@ZipCode", customerad.ZipCode); insertCommand.Parameters.AddWithValue("@Category", customerad.Category); insertCommand.Parameters.AddWithValue("@Title", customerad.Title); insertCommand.Parameters.AddWithValue("@Price", customerad.Price); insertCommand.Parameters.AddWithValue("@Images", customerad.Images); insertCommand.Parameters.AddWithValue("@Date_Time", customerad.Date_Time); insertCommand.Parameters.AddWithValue("@Description", customerad.Description); insertCommand.Parameters.AddWithValue("@Bussiness", customerad.Bussiness); insertCommand.Parameters.AddWithValue("@Payment", customerad.Payment); insertCommand.ExecuteNonQuery(); } result = "Ad registered!"; } else // User exists { string updateQuery = @"UPDATE customerad1 SET Name = @Name, Phone = @Phone, Country = @Country, ZipCode = @ZipCode, Category = @Category, Price = @Price, Images = @Images, Date_Time = @Date_Time, Description = @Description, Bussiness = @Bussiness, Payment = @Payment WHERE Id = @Id"; using (SqlCommand updateCommand = new SqlCommand(updateQuery, connad)) { updateCommand.Parameters.AddWithValue("@Name", customerad.Name); updateCommand.Parameters.AddWithValue("@Phone", customerad.Phone); updateCommand.Parameters.AddWithValue("@Country", customerad.Country); updateCommand.Parameters.AddWithValue("@ZipCode", customerad.ZipCode); updateCommand.Parameters.AddWithValue("@Category", customerad.Category); updateCommand.Parameters.AddWithValue("@Price", customerad.Price); updateCommand.Parameters.AddWithValue("@Images", customerad.Images); updateCommand.Parameters.AddWithValue("@Date_Time", customerad.Date_Time); updateCommand.Parameters.AddWithValue("@Description", customerad.Description); updateCommand.Parameters.AddWithValue("@Bussiness", customerad.Bussiness); updateCommand.Parameters.AddWithValue("@Payment", customerad.Payment); updateCommand.Parameters.AddWithValue("@Id", Id); updateCommand.ExecuteNonQuery(); } result = "Ad updated!"; } } } } catch (Exception ex) { // Handle and log the exception (e.g., write to a log file or display an error message). result = "An error occurred: " + ex.Message; } return result; }Jignesh KumarRank #91 · 22.9K reputationPosted Nov 4, 2023, 4:24 AM EDT
Yes, in update statement () not required.
Syntax:
Update tablename set columname = @newvalue where Id = @Id
Jignesh KumarRank #91 · 22.9K reputationPosted Nov 3, 2023, 11:28 AM EDT
Hi Venus,
Have you tried to debug your code.
int amountOfUsers = Convert.ToInt32(commandad.ExecuteScalar());commandad.CommandText = @"UPDATE customerad1 SET [Name]='" + customerad.Name + "', [Email]='" + customerad.Email + "', " + "[Phone]='" + customerad.Phone + "', " + "[Country]='" + customerad.Country + "', [ZipCode]='" + customerad.ZipCode + "', [Category]='" + customerad.Category + "', " + "[Title]='" + customerad.Title + "', [Price]='" + customerad.Price + "', [Images]='" + customerad.Images + "', " + "[Date_Time]='" + customerad.Date_Time + "', [Description]='" + customerad.Description + "', [Bussiness]='" + customerad.Bussiness + "', [Payment]='" + customerad.Payment + "' where [Id]='" + Id + "' "; commandad.ExecuteNonQuery(); result = "Ad updated!";One suggession, You can write your code in different way which is best practice as per software guide line, as part of coding standard we should use parameter rather then writing inline query you can conver your code to single store procedure like below and call from .net code,
Please refer this article which will help you out.
https://www.c-sharpcorner.com/blogs/insert-delete-and-update-using-stored-procedure-in-asp-net1
https://www.aspsnippets.com/Articles/GridView-CRUD-Select-Insert-Edit-Update-Delete-using-Single-Stored-Procedure-in-ASPNet.aspx
venus najadRank #2,456 · 573 reputationPosted Nov 3, 2023, 1:37 PM EDT
hello everyone and thnks for your replaies... mr *Amit i had used similar your codes, but it tells that Parameters.AddWithValue is old or @Email (and so on) not recognized... thanks for putting your time
mr jaimin and Jignesh thnks for your responds.. it worked. the problem was paranteses...
mr Jignesh, Convert.ToInt32(commandad.ExecuteScalar()) gives a value less than 1 if the item is not in the sql table and bigger than or equal 1 if the item is in the sql table...
thank your all and kind regards
Mehmet FatihRank #1,474 · 1.1K reputationPosted Nov 4, 2023, 5:05 AM EDT
If your id value is numeric then modify your code like that where [Id]=" + Id + "
Sam HobbsRank #107 · 20.5K reputationPosted Nov 4, 2023, 12:47 PM EDT
Also understand the importance of using the
try-catchstatement. Note that the sample code Amit Mohanty posted does. You can use thetry-catchstatement for each relevant statement, such as each call tocommandad.ExecuteNonQuery().Prasad RaveendranRank #320 · 7.8K reputationPosted Nov 4, 2023, 4:39 PM EDT
The issue with the update operation in your code seems to be with the syntax of the SQL update statement and the parameterization of the query. The
UPDATEstatement should not have([column]='value')syntax for each column. Instead, it should beSET column1 = value1, column2 = value2, ....Here's an adjusted version of your code using parameterized queries to prevent SQL injection and fix the update operation:
public static string AddAd(Customerad customerad, int Id) { string result; string q = string.Format("SELECT COUNT(*) FROM customerad1 WHERE Email='{0}' AND Title='{1}'", customerad.Email, customerad.Title); try { connad.Open(); commandad.CommandText = q; int amountOfUsers = Convert.ToInt32(commandad.ExecuteScalar()); if (amountOfUsers < 1) // new user { // Use parameterized query for INSERT to prevent SQL injection commandad.CommandText = @"INSERT INTO customerad1 (Name, Email, Phone, Country, ZipCode, Category, Title, Price, Images, Date_Time, Description, Bussiness, Payment) VALUES (@Name, @Email, @Phone, @Country, @ZipCode, @Category, @Title, @Price, @Images, @Date_Time, @Description, @Bussiness, @Payment)"; // Add parameters for the INSERT query commandad.Parameters.AddWithValue("@Name", customerad.Name); commandad.Parameters.AddWithValue("@Email", customerad.Email); // Add other parameters similarly commandad.ExecuteNonQuery(); result = "Ad registered!"; } else // user exists { // Use parameterized query for UPDATE commandad.CommandText = @"UPDATE customerad1 SET Name = @Name, Email = @Email, Phone = @Phone, Country = @Country, ZipCode = @ZipCode, Category = @Category, Title = @Title, Price = @Price, Images = @Images, Date_Time = @Date_Time, Description = @Description, Bussiness = @Bussiness, Payment = @Payment WHERE Id = @Id"; // Add parameters for the UPDATE query commandad.Parameters.AddWithValue("@Name", customerad.Name); commandad.Parameters.AddWithValue("@Email", customerad.Email); // Add other parameters similarly commandad.Parameters.AddWithValue("@Id", Id); commandad.ExecuteNonQuery(); result = "Ad updated!"; } } // Exception handling and closing connections should also be implemented // ... return result; }This code uses parameterized queries to prevent SQL injection and constructs the UPDATE query with proper SET column = value syntax. Make sure to handle exceptions and close connections appropriately in your code.
venus najadRank #2,456 · 573 reputationPosted Nov 5, 2023, 7:06 AM EST
hello everyone and thnaks for your responds to my update sql table issue. it is solved but i have another issure, which is how to conver my codes to base 64? my codes are as follow:
protected void ddlImage_SelectedIndexChanged(object sender, EventArgs e)
{
string selectedValue = ddlImage.SelectedItem.Value;
ShowImages(txtEmail.Text);
}
private void ShowImages(string email)
{
//get all filepath
string[] images = Directory.GetFiles(Server.MapPath("~/images/customers/" + email));
//get all files and add them to an arraylist
ArrayList imageList = new ArrayList();
foreach (string image in images)
{
string imageName = image.Substring(image.LastIndexOf(@"\") + 1);
imageList.Add(imageName);
}
// //set the arraylist as the dropdownlist's datasource and refresh
ddlImage.DataSource = imageList;
ddlImage.DataBind();
}
protected void btnuploadimage_Click(object sender, EventArgs e)
{
try
{
string folder = Server.MapPath("~/images/customers/" + txtEmail.Text);
if (!Directory.Exists(folder))
{
Directory.CreateDirectory(folder);
}
string filename = Path.GetFileName(FileUpload1.FileName);
FileUpload1.SaveAs(Server.MapPath("~/images/customers/" + txtEmail.Text + "/" + filename));
lblImage.Text = "image " + FileUpload1.FileName.ToString() + " successfully uploaded!";
Image1.ImageUrl = "~/images/customers/" + txtEmail.Text + "/" + filename;
Page_Load(sender, e);
}
catch (Exception)
{
lblImage.Text = "uppload Failed!";
}
}
i have found base 64 codes, but i ned help to use them on my codes.... i appreciate your help, thanks... the base 64 codes are:
for getting the image path
string DefaultImagePath = HttpContext.Current.Server.MapPath("~/NoImage.jpg");
byte[] imageArray = System.IO.File.ReadAllBytes(DefaultImagePath);
string base64ImageRepresentation = Convert.ToBase64String(imageArray);
now i for converting the base 64 string to byte array that converts to memorystream:
byte[] bytes = Convert.FromBase64String(base64ImageRepresentation);
using (MemoryStream ms = new MemoryStream(bytes))
{ pic.Image = Image.FromStream(ms); }
i appreciate any help... specialy if you give me the codes, thanks nd very kind regards