I have made a post form where "professors should enter their username and password to be able to post,and I don't get any error about it.
but when I run it, even if I enter the right username and password, it would always just do the "else" command.
Here's my code
protected void Button9_Click(object sender, EventArgs e)
{
string postname = this.Postuser.Text;
string postpass = this.Postpass.Text;
string posttitle = this.TOP.Text;
string postbody = this.BOP.Text;
string sqlstr2 = "select * from professors WHERE pname='" + Postuser + "' AND ppass='" + Postpass + "'";
DataTable dt1 = DBFunction.SelectFromTable(sqlstr2, "DBS.accdb");
if (dt1.Rows.Count > 0)
{
string sqlpost2 = "insert into post2(Professor,Title,Body)";
sqlpost2 += "value('" + postname + "','" + posttitle + "','" + postbody + "')";
DBFunction.ChangeTable(sqlpost2, "DBS.accdb");
}
else
this.Label1.Text = "Posting on this wall is only allowed for profesors and it seems that you're not one";
DataList1.DataBind();
}
In the following line of code, you are trying to concatenate PostUser and PostPass controls instead of their text properties
The following code should be changed:
string sqlstr2 = "select * from professors WHERE pname='" + Postuser + "' AND ppass='" + Postpass + "'";
Update your code like this to postname and postpass variables which are holding text values of user and password
string sqlstr2 = "select * from professors WHERE pname='" + postname + "' AND ppass='" + postpass + "'";
Note: Your code in vulnerable to sql injection attacks so you must use parameterized query
I'm getting syntax error in all my inputs into the textboxes.
In my database all the requirement is string other than the ID which is an autonumber, I try to search for possible answer but all didn't work or maybe I just missed some answer
Here is the error:
Syntax error (missing operator) in query expression ''hasdasd'password
= 'h'account_Type='Manager'Name='h'Middle_Name='h'Surname'h'address'h'BirthDate='3/17/1999'Mobile_Number'65465''.
Code:
private void update_Click(object sender, EventArgs e)
{
DateTime bdate = DateTime.Parse(birthdate.Value.ToShortDateString());
DateTime currentDate = DateTime.Parse(DateTime.Now.Date.ToShortDateString());
int age = currentDate.Year - bdate.Year;
String id = emp_view.SelectedRows[0].Cells[0].Value + String.Empty;
int id1 = Int32.Parse(id);
try
{
OleDbConnection con = new OleDbConnection();
con.ConnectionString = #"Provider = Microsoft.ACE.OLEDB.12.0; Data Source = C:\dbms\jollibee.accdb";
con.Open();
OleDbCommand cmd = new OleDbCommand();
cmd.Connection = con;
cmd.CommandText = "update Employee_Details set username = '" + username.Text +
"'password = '" + password.Text +
"'account_Type='" + accountType.Text +
"'Name='" + name.Text +
"'Middle_Name='" + middlename.Text +
"'Surname'" + surname.Text +
"'address'" + address.Text +
"'BirthDate='" + birthdate.Value.ToShortDateString() +
"'Mobile_Number'" + mobilenumber.Text +
"'where ID = '" + id1 + "'";
if (username.Text.Equals("") ||
username.Text.Equals("") ||
password.Text.Equals("") ||
middlename.Text.Equals("") ||
surname.Text.Equals("") ||
address.Text.Equals("") ||
accountType.Text.Equals("") ||
mobilenumber.Text.Equals("")
)
{
MessageBox.Show("Please fill all fields.");
con.Close();
}
else if (age < 18)
{
MessageBox.Show("You are not allowed to work because you are under age..");
con.Close();
}
else
{
cmd.ExecuteNonQuery();
con.Close();
MessageBox.Show(username.Text + "is now updated on database.");
list();
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
In your existing code, there are issues like.
1- Column in update are not separated by ","
2- All string are not separated using quotes ''
You should always avoid writing queries inline by concatenation of string. This will make you code vulnerable to SQL Injection.
To read more about SQL Injections check here
Change your code like following using command parameters.
cmd.CommandText = "update Employee_Details set [username] = #un, [password] = #pw, [account_Type]= #at, [Name] = #nm, [Middle_Name]= #mn, [Surname]= #sn, [address]= #add, [BirthDate] = #bd, [Mobile_Number] = #mn WHERE [Id]=#id";
cmd.Parameters.Add("#un", OleDbType.VarChar).Value = username.Text;
cmd.Parameters.Add("#pw", OleDbType.VarChar).Value = password.Text;
cmd.Parameters.Add("#at", OleDbType.VarChar).Value = accountType.Text;
cmd.Parameters.Add("#nm", OleDbType.VarChar).Value = name.Text;
cmd.Parameters.Add("#mn", OleDbType.VarChar).Value = middlename.Text;
cmd.Parameters.Add("#sn", OleDbType.VarChar).Value = surname.Text;
cmd.Parameters.Add("#add", OleDbType.VarChar).Value = address.Text;
cmd.Parameters.Add("#bd", OleDbType.Date).Value = Convert.ToDateTime(birthdate.Value);
cmd.Parameters.Add("#mn", OleDbType.VarChar).Value = mobilenumber.Text;
cmd.Parameters.Add("#id", OleDbType.VarChar).Value = id1;
Note: You need to correct the datatype based on your table structure as it is now known to me.
Your completely malformed SQL should look like:
cmd.CommandText = "update Employee_Details set " +
"username = '" + username.Text + "',"+
"[password] = '" + password.Text + "'," +
"account_Type = '" + accountType.Text + "'," +
"[Name] = '" + name.Text + "'," +
"Middle_Name = '" + middlename.Text + "'," +
"Surname = '" + surname.Text + "'," +
"address = '" + address.Text + "'," +
"BirthDate = #" + birthdate.Value.ToString("yyyy'/'MM'/dd") + "#," +
"Mobile_Number = '" + mobilenumber.Text + "' " +
"where ID = " + id1 + "";
That said, DO use parameters as already explained. Much easier and safer.
Data comes from "Temp" table.
Stored in variables
Inserted into "Client" table with the addition of two more variables.
And there comes an error. The INSERT query is not executing properly.
Query,
int r;
string que = "INSERT INTO client (fname, lname, dob,
email, gender, uname, upass) VALUES
('" + fname + "',
'" + lname + "', '" + dob + "',
'" + email + "',
'" + gender + "',
'" + TextBox1.Text + "',
'" + TextBox2.Text + "') ";
r = c.savedeldata(que);
savedeldata Function
public int savedeldata(string qu)
{
con.Open();
cmd = new SqlCommand(qu, con);
int i = cmd.ExecuteNonQuery();
con.Close();
return i;
}
That's the only solution I can find.
if (ds.Tables["0"].Rows.Count == 1)
{
int r;
string queryt = "DELETE FROM tbl_client";
r = c.savedeldata(queryt);
string que = "INSERT INTO tbl_client(fname, lname, dob, email, gender) SELECT * FROM temp WHERE dob = '" + TextBox3.Text + "'";
r = c.savedeldata(que);
string quer = "UPDATE tbl_client SET uname = '"+ TextBox1.Text +"', upass = '"+ TextBox2.Text +"' WHERE dob = '"+ TextBox3.Text +"'";
r = c.savedeldata(quer);
}
I am assigning the value to the variable from the text box on the page during the pageupload event of AjaxFileUpload1.The problem is that, I am not getting the value from the text box to my variable even though no error throws.My variables are
string scn = txtSCN.Text;
string line1 = txtLineitem.Text;
string aging1 = txtAging.Text;
Any idea why AjaxFileUpload1_UploadComplete is not able to read text box value
My cs Code is:
protected void AjaxFileUpload1_UploadComplete(object sender, AjaxControlToolkit.AjaxFileUploadEventArgs e)
{
string c = System.IO.Path.GetFileName(e.FileName);
string dpath = "~/Profile/Images/";
string scn = txtSCN.Text;
string line1 = txtLineitem.Text;
string aging1 = txtAging.Text;
AjaxFileUpload1.SaveAs(MapPath(Path.Combine(dpath,c)));
dpath = dpath + c;
string str1 = ConfigurationManager.ConnectionStrings["ProTracConnGMCH"].ConnectionString;
SqlConnection cn = new SqlConnection(str1);
cn.Open();
string sql = "Update tbNoquoteFollowupupdate set MailreceivedURL = '" + dpath + "', chkMailreceived = 1 , Buyername = '" + buyername + "' where scn = '" + scn + "' AND lineItem = '" + line1 + "' and Aging ='" + aging1 + "' ";
SqlCommand cmd = new SqlCommand(sql, cn);
int i = cmd.ExecuteNonQuery();
if (i > 0)
{
// AjaxFileUpload1.SaveAs(Path.Combine(dpath, e.FileName));
//AjaxFileUpload1.SaveAs(MapPath(dpath));
}
cn.Close();
BindGridviewData1();
cn.Open();
string cmd2 = "Insert Into tbMulitmailsreived (scn, lineItem,followupdate, Aging,MailreceivedURL) Values ('" + scn + "', '" + line1 + "','" + DateTime.Now + "','" + aging1 + "','" + dpath + "')";
SqlCommand sqlCommand2 = new SqlCommand(cmd2, cn);
sqlCommand2.ExecuteNonQuery();
cn.Close();
}
Please help me
I spent some time last week investigating this question but in the end couldn't find an easy solution for this. The OP in that question solved it by storing values in the Session but for this to work you would still need to cause a postback at some stage.
There apparently was functionality planned for the AjaxFileUpload control to pass values in the Context Keys collections but this was never implemented. This question describes how to implement this yourself though.
I think I saw another question around the same topic and the OP solved it by changing to using the AsyncFileUpload control but I stand to be corrected...
i think you need to add !Page.IsPostBack to your code. like this
protected void AjaxFileUpload1_UploadComplete(object sender, AjaxControlToolkit.AjaxFileUploadEventArgs e)
{
if(!Page.IsPostBack)
{
string c = System.IO.Path.GetFileName(e.FileName);
string dpath = "~/Profile/Images/";
string scn = txtSCN.Text;
string line1 = txtLineitem.Text;
string aging1 = txtAging.Text;
AjaxFileUpload1.SaveAs(MapPath(Path.Combine(dpath,c)));
dpath = dpath + c;
string str1 = ConfigurationManager.ConnectionStrings["ProTracConnGMCH"].ConnectionString;
SqlConnection cn = new SqlConnection(str1);
cn.Open();
string sql = "Update tbNoquoteFollowupupdate set MailreceivedURL = '" + dpath + "', chkMailreceived = 1 , Buyername = '" + buyername + "' where scn = '" + scn + "' AND lineItem = '" + line1 + "' and Aging ='" + aging1 + "' ";
SqlCommand cmd = new SqlCommand(sql, cn);
int i = cmd.ExecuteNonQuery();
if (i > 0)
{
// AjaxFileUpload1.SaveAs(Path.Combine(dpath, e.FileName));
//AjaxFileUpload1.SaveAs(MapPath(dpath));
}
cn.Close();
BindGridviewData1();
cn.Open();
string cmd2 = "Insert Into tbMulitmailsreived (scn, lineItem,followupdate, Aging,MailreceivedURL) Values ('" + scn + "', '" + line1 + "','" + DateTime.Now + "','" + aging1 + "','" + dpath + "')";
SqlCommand sqlCommand2 = new SqlCommand(cmd2, cn);
sqlCommand2.ExecuteNonQuery();
cn.Close();
}
}
Hie.
So what I'm trying to do is insert a null value in an integer column in MySQL using a C# application.
I'm aware the query to generally do such a thing would be;
INSERT INTO Database.Table (IntColumn) VALUES (NULL);
UPDATE Database.Table set IntColumn = (NULL) where id = '1';
It works great in workbench. Thing is, I'm not even sure if this is possible but I need to do this in C# while still allowing the textbox the flexibility to enter integers into the MySQL database. In this case 'home.text' which is linked up to 'home' column in MySQL which is an integer field.
This is how I made my code.
using MySql.Data.MySqlClient;
using MySql.Data;
namespace Masca.Content
{
/// <summary>
/// Interaction logic for Login.xaml
/// </summary>
public partial class Login : UserControl
{
//Function to check if column value is null before fetching string
public static string GetString(MySqlDataReader reader, string colName)
{
if (reader[colName] == DBNull.Value)
return string.Empty;
else
return (string)reader[colName];
}
//Function to check if column value is null before fetching int as string
public static string GetColumnValueAsString(MySqlDataReader reader, string colName)
{
if (reader[colName] == DBNull.Value)
return string.Empty;
else
return reader[colName].ToString();
}
public Login()
{
InitializeComponent();
}
public void save_Click(object sender, RoutedEventArgs e)
{
//Authentication parameters
string sqlcon = "datasource = localhost; port = 3306; username = root; password = root";
//Query to excecute
string queryadd = "insert into users.employees (member, username, password, question, answer, first, second, third, surname, dob, gender, doc, dept, cell, home, work, email, pemail, street, surbub, city, region, position, access, privilages, bank, account) values ('" + this.member.Text + "','" + this.username.Text + "','" + this.password.Text + "', '" + this.question.Text + "','" + this.answer.Text + "', '" + this.first.Text + "','" + this.second.Text + "','" + this.third.Text + "','" + this.surname.Text + "', '" + this.dob.Text + "','" + this.gender.Text + "', '" + this.doc.Text + "', '" + this.dept.Text + "', '" + this.cell.Text + "','" + this.home.Text + "', '" + this.work.Text + "', '" + this.email.Text + "', '" + this.pemail.Text + "', '" + this.street.Text + "', '" + this.surbub.Text + "', '" + this.city.Text + "', '" + this.region.Text + "', '" + this.position.Text + "', '" + this.access.Text + "', '" + this.privilages.Text + "', '" + this.bank.Text + "', '" + this.account.Text + "') ; insert into logon.login (username, password) values ('" +this.username.Text+ "', '" +this.password.Text+ "'); select * from users.employees where member = '" + this.member.Text + "' ;";
MySqlConnection con = new MySqlConnection(sqlcon);
MySqlDataReader rdr;
MySqlCommand cmd = new MySqlCommand(queryadd, con);
// Excecution
try
{
con.Open();
rdr = cmd.ExecuteReader();
MessageBox.Show("Saved");
while (rdr.Read())
{
//Declarations using function
string stag = GetColumnValueAsString(rdr, "tag");
string snumber = GetColumnValueAsString(rdr, "tag");
string smember = GetColumnValueAsString(rdr, "member");
string susername = GetString(rdr, "username");
string spassword = GetString(rdr, "password");
string ssecurity = GetString(rdr, "question");
string sanswer = GetString(rdr, "answer");
string sfirst = GetString(rdr, "first");
string ssecond = GetString(rdr, "second");
string sthird = GetString(rdr, "third");
string sfourth = GetString(rdr, "surname");
string sdob = rdr.GetString("dob");
string sgender = rdr.GetString("gender");
string sdoc = rdr.GetString("doc");
string sdept = rdr.GetString("dept");
string scell = GetColumnValueAsString(rdr, "cell");
string shome = GetColumnValueAsString(rdr, "home");
string swork = GetColumnValueAsString(rdr, "work");
string semail = GetString(rdr, "email");
string spemail = GetString(rdr, "pemail");
string sstreet = GetString(rdr, "street");
string ssurbub = GetString(rdr, "surbub");
string scity = GetString(rdr, "city");
string sregion = GetString(rdr, "region");
string sposition = GetString(rdr, "position");
string saccess = GetString(rdr, "access");
string sprivilages = GetString(rdr, "privilages");
string sbank = GetString(rdr, "bank");
string saccount = GetString(rdr, "account");
//Binding strings to textboxes
tag.Text = stag;
number.Text = stag;
member.Text = smember;
username.Text = susername;
password.Text = spassword;
question.Text = ssecurity;
answer.Text = sanswer;
first.Text = sfirst;
second.Text = ssecond;
third.Text = sthird;
surname.Text = sfourth;
dob.Text = sdob;
gender.Text = sgender;
doc.Text = sdoc;
dept.Text = sdept;
cell.Text = scell;
home.Text = shome;
work.Text = swork;
email.Text = semail;
pemail.Text = spemail;
street.Text = sstreet;
surbub.Text = ssurbub;
city.Text = scity;
region.Text = sregion;
position.Text = sposition;
access.Text = saccess;
privilages.Text = sprivilages;
bank.Text = sbank;
account.Text = saccount;
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
This is the code behind a form that contains employee details. home.text is supposed to hold the home land line number. Assuming the employee doesn't have a land line at home, they would leave the field blank.
Everytime I do that however, I get an exception thrown saying "Incorrect integer value". To leave it blank in the database, I would have to type (NULL) where '"this.home.text'" currently is in the query. If i do that though, I wont be able to insert information into the database using home.text when need be.
Anyother way to do this?
Insert Usual preamble about your SQL being open to injection attacks (see this question for more information on parameterized SQL).
The problem is, you're inserting strings in to all the columns, irrespective of the underlying database type.
this:
'" + this.home.text + "'
If blank, will produce '', which cannot be converted to an integer. You might want to try something like:
int? homeNumber = null; // Note the int? is syntactic sugar for Nullable<int>
if(!string.IsNullOrEmpty(home.text))
homeNumber = Convert.ToInt32(home.Text);
And insert thusly:
," + homeNumber + ",.... etc.
You could try something along the lines of
if (!int.TryParse(shome, out home.Text))
home.Text = null;
I think instead you should just check for empty or null strings,
string queryadd = "insert into users.employees (member, username, password, question, answer, first, second, third, surname, dob, gender, doc, dept, cell, home, work, email, pemail, street, surbub, city, region, position, access, privilages, bank, account) values ('"
+ this.member.Text + "','" + this.username.Text + "','" + this.password.Text + "', '" + this.question.Text + "','" + this.answer.Text + "', '" + this.first.Text + "','" + this.second.Text + "','" + this.third.Text
+ "','" + this.surname.Text + "', '" + this.dob.Text + "','" + this.gender.Text + "', '" + this.doc.Text + "', '" + this.dept.Text + "', '" + this.cell.Text + "','"
+ string.IsNullOrWhiteSpace(this.home.Text) ? null : this.home.Text + "', '"
+ this.work.Text + "', '" + this.email.Text + "', '" + this.pemail.Text + "', '" + this.street.Text + "', '" + this.surbub.Text + "', '" + this.city.Text + "', '" + this.region.Text + "', '" + this.position.Text + "', '"
+ this.access.Text + "', '" + this.privilages.Text + "', '" + this.bank.Text + "', '" + this.account.Text
+ "') ; insert into logon.login (username, password) values ('" + this.username.Text + "', '" + this.password.Text + "'); "
+ " select * from users.employees where member = '" + this.member.Text + "' ;";
look at string.IsNullOrWhiteSpace(this.home.Text) ? null : this.home.Text
I don't think so the SQL that you have formed is right and will work like this, i.e. two SQL separated by ; and also has SELECT SQL merged with INSERT