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.
Related
public function registration_insert($data) {
//$this->db->trans_start();
//echo "<pre>";print_r($_POST);die;
// Query to check whether username already exist or not
$condition = "user_name =" . "'" . $data['user_name'] . "'";
$this->db->select('*');
$this->db->from('user_login');
$this->db->where($condition);
$this->db->limit(1);
$query = $this->db->get();
// Query to insert data in database
$this->db->insert('user_login', $data);
if ($this->db->affected_rows() > 0) {
return true;
}
This is my program. It is not executing this code. I want to store the data in the database. Explicitly, with print_r(), it is posting the data but it is not storing it in the database and it is showing error.
First of all, i want to check your $data variable , if $data is not an object that have the sames attribute name like your database table column that will give you a problem.
I mean, for exemple if your user_login table have tow column (id , user_name), you should have in the $data object the same name of attributes
and to verify if your query work correctly just your code will be like this :
$q = $this->db->insert('user_login', $data);
if ($q) {
return $this->db->insert_id();
} else {
return false;
}
I am using vtiger 6.1.0 version.I want to fetch the user details from the database in the vtiger.
My code:
require_once('include/database/PearDatabase.php');
$db = PearDatabase::getInstance();
$query8 = "SELECT id from vtiger_users where is_admin=?";
$result8 =$db->pquery($query8, array("on"));
echo $num_rows = $db->num_rows($result8);
for($i=0; $i<$num_rows; $i++) {
echo $row = $db->query_result_rowdata($result8, $i,'id');
}
While using this code, the total number of rows is printed, but each id can not be fetched, showing some internal server error. Please help me!
You can pass only two argument in query_result_rowdata function.
Please see function in include/database/PearDatabase.php file.
function raw_query_result_rowdata(&$result, $row=0) {
if (!is_object($result))
throw new Exception("result is not an object");
$result->Move($row);
$rowdata = $this->change_key_case($result->FetchRow());
return $rowdata;
}
So please use like that, it work for me.
$index = 0;
foreach($listViewEntries as $recordId => $record) {
$rawData = $db->query_result_rowdata($listResult, $index++);
}
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).
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.
In my CakePHP forms_controller I have:
var $uses=array('Form','Field');
// ...
$this->set('retrived',$this->Field->find("all",array('conditions'=>array('Field.formname'=>$formname,))));
and in the view:
<?php foreach ($retrived as $r): ?>
<?php echo $r['Field']['fieldname']; ?><br>
<?php endforeach; ?>
I'm not getting the answer for it
Actually my table fields wil be like:
fieldname
formname
type
value
More details from my forms_controller:
function views()
{
if (!empty($this->params['form']))
{
$this->set('fieldctr',$this->params['form']['formfieldctr']);
$fieldctr=$this->params['form']['formfieldctr'];
if(!empty($this->params['form']['formnameelements']))
{
$this->set('formname',$this->params['form']['formnameelements']);//formname
$this->Form->saveField('name',$this->params['form']['formnameelements']);
}
else
{
$this->set('formname','MyForm');//formname
$this->Form->saveField('name','MyForm');
}
$this->Form->saveField('body',$this->params['form']['formelements']);//inserts into database
$ret = $this->Form->query("Select id from forms order by id DESC LIMIT 1");
$newid=$ret[0]['forms']['id'];echo $newid;
$upd=$this->Form->query("update forms set ctr=$fieldctr where id= $newid");
$formname=$this->params['form']['formnameelements'];
$n="$formname";
$array = $this->params['form']['formfieldnameelements'];
$comma_separated = explode(",", $array);
for($i=0;$i<$fieldctr;$i++)
{
echo $comma_separated[$i];
echo " ";
$n="$comma_separated[$i]";
//insert the fields of each form to the table fields
$this->data['Field']['fieldname'] = $comma_separated[$i];
$this->data['Field']['formname'] = $formname;
$this->Field->saveAll($this->data);
}
The above method is where I'm inserting the formname in my forms table.
And inserting that formname with their fieldsname in the fields table:
function formupdate()
{
$this->set('fieldctr',$this->params['form']['formfieldctr']);
$fieldctr=$this->params['form']['formfieldctr'];
$this->set('formname',$this->params['form']['formnameelements']);//formname
$formname=$this->params['form']['formnameelements'];
$ret = $this->Field->query("SELECT fieldname FROM fields WHERE fields.formname = "."'$formname'"."order by id ASC");
for($q=0;$q<$fieldctr;$q++)
{
$fieldname[$q]=$ret[$q]['fields']['fieldname'];
}
$this->set('retrived',$this->Field->find("all",array('conditions'=>array('Field.formname'=>$formname))));
$array = $this->params['form']['formfieldvalueelements'];
$comma_separated = explode(",", $array);
for($i=0;$i<$fieldctr;$i++)
{
echo $comma_separated[$i];
echo " ";
$n="$comma_separated[$i]";
echo $fieldname[$i];
$this->Field->updateAll(array('Field.value' => "'$comma_separated[$i]'"),array('Field.fieldname' => $fieldname[$i],'Field.formname'=>$formname));
}
$this->set('retrived',$this->Field->find("all",array('conditions'=>array('Field.formname'=>$formname,))));
} // end of function formupdate
In the above formupdate method I'm inserting the values of the corresponding values of that fields in the fields table... All the values are inserted correctly - but in my formupdate.ctp view:
Nothing is displayed in my view... eventhough the content is there in the table..
Please resolve my problem
By the names of your models, I think it's safe to conclude that you're trying to ouput some HTML. Since the question isn't really complete (where is the code?), we can't tell what's wrong with it.
A wild guess would be that something is being stripped there or ignored by your browser.
Aruna,
Please post the code you're using! It's possible that the error is something small, but without knowing what you're doing, it's impossible to help more than dr. Lecter did.
When you say that the fields table is updated correctly, do you mean that you can safely invoke the Model::save() method? Are you then calling Model::read() or Model::find() in the controller, then using the returned values from that to set a variable that can be accessed in the view?