C# login message warning - database

Well im here because i have a problem. i have code that was created a while ago. my code is working properly when i a user type the correct username and password. so my problem is when a user insert wrong username and password error message wont show. Here is my code:
MyDs.Clear();
MyDa.SelectCommand = Conn.CreateCommand();
MyDa.SelectCommand.CommandText =
"select * from PersonalName where Firstname=#first and Lastname=#last";
MyDa.SelectCommand.CommandType = CommandType.Text;
MyDa.SelectCommand.Parameters.Add("#first", DbType.String, 25, "Firstname").Value = textbox_Username.Text;
MyDa.SelectCommand.Parameters.Add("#last", DbType.String, 25, "Lastname").Value = textbox_Password.Text;
MyDa.Fill(MyDs);
foreach (DataRow item in MyDs.Tables[0].Rows)
{
if (textbox_Username.Text != item[1].ToString() || textbox_Password.Text != item[3].ToString())
{
MessageBox.Show("not connected");
}
else
{
MessageBox.Show("Connected");
}
}
Anyone can tell me what is the problem with this code?

Your dataset will be empty if they put in the wrong username. This will be closer to what you want:
if (MyDs.Tables[0].Rows.Count > 0)
{
// you don't need to check username, the SQL query took care of that
if (textbox_Password.Text == item[3].ToString())
MessageBox.Show("Connected.");
else
MessageBox.Show("Failed."); // wrong password
}
else
MessageBox.Show("Failed."); // no such user

if the query returns no records becasue firast and last name aren't present, foreach doesn't execute nothing happens...
You need to test for myDa being empty as well, your code only works for checking valid users.

Related

Can't update Boolean value in Apex

I cannot update update this Boolean value in Apex. What is going wrong? The if statement, and the fact that the front end representation is a checkbox, proves that it is indeed a boolean value. I am new to Apex so I feel its a basic misunderstanding of how it works. Can anyone help me out?
Here is the code that I'm executing in an Anonymous Window.
Account acc = new Account(Name='Test Name');
if (acc.Do_Not_Contact__pc == false) {
System.debug('DNC is false');
} else {
System.debug('DNC is true');
}
insert acc;
acc.Do_Not_Contact__pc = true;
update acc;
It fails on the second to last line, displaying the following message:
System.DmlException: Update failed. First exception on row 0 with id 001W000000fFiVbIAK; first error: INVALID_FIELD_FOR_INSERT_UPDATE, Account: bad field names on insert/update call: Do_Not_Contact__pc: [Do_Not_Contact__pc]
What's particularly frustrating is that when I change the second to last line to
acc.Do_Not_Contact__pc = 'true';
I get an error stating that I cannot assign a String to a Boolean value
Remove the single quotes and I assume you typed the field name wrong. Try acc.Do_Not_Contact__c = true;

Syntax error in FROM clause Access

I want to read the data from Access Database in order to check if a password is correct or not. I use this code:
var check=false;
OleDbCommand c = new OleDbCommand();
c.Connection = co //the connection to the Database;
c.CommandText = "select * FROM User Where user_name='"+usee+"'";
OleDbDataReader re = c.ExecuteReader();
while (re.Read())
{
if (re.ToString() == pasy)
{
check = true;
}
}
It gives me a "Syntax error in FROM clause." when the code executes.
"User" is a reserved word for Access.
Here is a list of reserved words :
http://support.microsoft.com/kb/286335/en-us
and here is a page describing that problem :
http://support.microsoft.com/kb/181489/en-us

joomla - Storing user parameters in custom component issue

Hi for my custom component I need to set some custom parameters for joomla user for membership for checking if the user ni trial period or not and it can be change from the component admin panel for specific user.
The problem arises while retrieving the parameter. I think it is stored in cookie and it isn^t updated. I wrote the code like that to check it.
$user = JFactory::getUser(JRequest::getVar('id','0'));
echo $user->getParam('trialPeriod','0');
to save the value I am useing JHTML booleanlist.
$user->setParam('trialPeriod',$data['trialPeriod']);
$user->save();
Then is stores the value in joomla users table in the row of that user with column of params as;
{"trialPeriod":"0"}
in this situation it echoes the value as 0. Then I am changin the state of trialPeriod var as 1 and storing in db it updates the db as;
{"trialPeriod":"1"}
After all I am refreshing the page where the value is prompt the the screen the the value remains still the same as 0;
To clarify;
First of all there is no problem with saving the param it is changed properly. The problem is retrieving the changed one. The releated piece of code is following;
$user = JFactory::getUser();
$doc = JFactory::getDocument();
if($user->getParam('trialPeriod',0) == 0){
$ed = JFactory::getDate($obj->expirationDate);//obj is user from custom table and there is no problem with getting it.
$isTrialEnd = FALSE;
}else{
$ed = JFactory::getDate($user->getParam('trialExp',0));
$isTrialEnd = TRUE;
}
if($isTrialEnd){
//do something else
}else{
echo $user->getParam('trialPeriod','0');
}
actually big part of the code is unneccessary to explain it but you will get the idea.
What is the solution for this?
Editted.
$app = JFactory::getApplication();
$config = JFactory::getConfig();
$db = $this->getDbo();
$isNew = empty($data['uid']) ? true : false;
$params = JComponentHelper::getParams('com_dratransport');
if($isNew){
// Initialise the table with JUser.
$user = new JUser;
// Prepare the data for the user object.
$username = self::getCreatedUserName($data['type']);
$data['username'] = !empty($data['username']) ? $data['username'] : $username;
$data['password'] = $data['password1'];
$useractivation = $params->get('useractivation');
// Check if the user needs to activate their account.
if (($useractivation == 1) || ($useractivation == 2)) {
$data['activation'] = JApplication::getHash(JUserHelper::genRandomPassword());
$data['block'] = 1;
}
}else{
$user = JFactory::getUser($data['uid']);
$data['password'] = $data['password1'];
}
$membership = DraTransportHelperArrays::membershipCFG();
$membership = $membership[$data['membership']];
if($data['membership'] == 4)
$data['groups'] = array($params->get('new_usertype',2),$params->get($membership,2));
else
$data['groups'] = array($params->get($membership,2));
$data['name'] = $data['companyName'];
$user->setParam('trialPeriod',$data['trialPeriod']);
// Bind the data.
if (!$user->bind($data)) {
$this->setError(JText::sprintf('COM_USERS_REGISTRATION_BIND_FAILED', $user->getError()));
return false;
}
// Load the users plugin group.
JPluginHelper::importPlugin('user');
// Store the data.
if (!$user->save()) {
$app->enqueuemessage($user->getError());
$this->setError(JText::sprintf('COM_USERS_REGISTRATION_SAVE_FAILED', $user->getError()));
return false;
}
this piece of code is for storing the data releated with the users table.
Turns out this was the fact that Joomla stores the JUser instance in the session that caused the problem.
When changing a user's parameters from the back-end, the changes are not reflected in that user's session, until she logs out and back in again.
We could not find an easy option to modify anther user's active session, so we resorted to the use of a plugin that refreshes the JUser instance in the logged-in users' session, something like the following:
$user = JFactory::getUser();
$session = JFactory::getSession();
if(!$user->guest) {
$session->set('user', new JUser($user->id));
}
(reference: here).

Inserting variables in mysql queries

I've written a function which updates the mysql database row with some new column data.
Here is the function:
function sql($set,$data){
$sql = mysql_query("UPDATE members SET '".$set."' = '".$data."' WHERE login = '".$_SESSION['login']."'");
if($sql){
echo 'Profile updated.';
}
else{
echo 'Could not update profile. Please try again later.';
}
}
And here is a fragment from the program which is supposed to utilise the function:
$array = array("$password", "$email", "$age");
if($array[0] != 0){
sql("password",$password);
}
if($array[1] != 0){
sql("email",$email);
}
if($array[2] != 0){
sql("age",$age);
}
It doesn't write the values to the database. What's wrong? Maybe it's the quotation of the variables in the function?
Remove the single quote on the SET :
function sql($set,$data){
$sql = mysql_query("UPDATE members SET ".$set." = '".$data."' WHERE login = '".$_SESSION['login']."'");
if($sql){
echo 'Profile updated.';
}
else{
echo 'Could not update profile. Please try again later.';
}
}
Column names don't dont need to be quoted
Working example here -> http://www.sqlize.com/c34I44c37r
It is indeed the quotation. To be specific, it's the quotation for the filed name (name, email, ..)
Just ` instead of '
SET `foo` = 'bar'
PS: Please make sure that you escape the user input before writing it to db using mysql_real_escape_string($data). Otherwise one could alter your query, which is called mysql injection.

Android:Is there a better way to insert and/or update a database entry?

I have a database containing a userId and a note. The user doesn't know if there already is a note in the DB so they write one and click the 'Submit' button. I want to insert this note if there is no note for the userId or update that userId's already existing note:
notesDb.open();
boolean updateResult = notesDb.updateMessage(
userId,
details_notes_input.getText().toString());
if(updateResult == true) {
Log.d("databaseTester", "Updated entry into table");
} else {
Log.d("databaseTester", "FAILED to update entry into table");
long insertResult = notesDb.insertMessage(
userId,
details_notes_input.getText().toString());
if(insertResult == -1){
Log.d("databaseTester", "Failed to insert entry into table");
} else {
Log.d("databaseTester", "Inserted entry into table");
}
}
notesDb.close();
So, I'm pretty much attempting to 'update' an entry and if I fail then I attempt to 'insert' it. I don't know SQL very well, but I would think there would be a better way. Thanks.
It sounds like you could use sqlite's REPLACE to solve this problem, using SQLiteDatabase.replace().
You can catch a constraint exception launched in case of previous ID existence and then update.
try {
db.insertOrThrow("sometable", null, cv);
} catch (SQLiteConstraintException e) {
db.update("sometable", cv,"sometable_uid =" + id, null);
}
Try this
result = db.insertWithOnConflict("tablename ", null, cv, -1);

Resources