$credit = $this->db->select('credits');
$this->db->from('users');
$this->db->where('refferal_code',$refferal_code);
$data1 = array('credits'=>$credit + 10);
$this->db->update('users',$data1);
I need to update a column in a database..
When a user signs up, he will give a referral code.
I need to check whether that code exists in the database and need to update the referral code for the user by giving him with 10 more credits.
The above code shows error, Can anyone help me me figure why?
Try this
$credit = $this->db->select('credits');
$this->db->from('users');
$this->db->where('refferal_code',$refferal_code);
$data = $this->db->get();
if($data->num_rows()>0)
{
$res = $data->row_object();
$this->db->where('refferal_code',$refferal_code);
$update = $this->db->update('users',array('credits'=>$res->credits + 10));
}
OR
Simplest one as #Shaiful Islam mentioned in comment
$this->db->from('users');
$this->db->where('refferal_code',$refferal_code);
$this->db->set('credits', 'credits+10', FALSE);
$this->db->update('users');
Related
I need help to help me correct my php function in codeigniter.
I have a database; I want addirionner all values of " from_user_id ".
Check data
I use this sql to get the desired result.
SELECT SUM(kiff_envoi+kiff_recu+visite_recu+profile_visite+da_recu+da_envoi+topic_poster+repon_topic+conv_envoi+conv_recu) AS total_stats FROM score WHERE from_user_id = ?
In codeingniter I use this function.
It allows me to check if " from_user_id " exists, if it exists, we calculate the total different tables and we update the result in " total_stats ". If " from_user_id " does not exist, create it.
But my function does not return me the right result.
I had to make a big mistake but I do not know where!
Does someone could help me please.
public function count_tout_stats($user_id) //total des stats
{
$this->db->select_sum(conv_recu, conv_envoi, repon_topic, etc...);
$query = $this->db->from('score');
$this->db->where('from_user_id', $user_id);
$total_stats = $this->db->count_all_results();
if ($this->ttl_stats_score($user_id) > 0) // Check if exists
{
$data = array(
'total_stats' => $total_stats
);
$this->db->where('from_user_id', $user_id);
$this->db->update('score', $data);
}
else
{
$data = array(
'from_user_id' => $user_id,
'total_stats' => $total_stats
);
$this->db->insert('score', $data);
}
return $total_stats;
}
public function ttl_stats_score($user_id)
{
$this->db->where('from_user_id', $user_id);
$this->db->from('score');
return $this->db->count_all_results();
}
Thank you in advance for your assistance
Violette
You can try this:
$this->db->select('(kiff_envoi+kiff_recu+visite_recu+profile_visite+da_recu+da_envoi+topic_poster+repon_topic+conv_envoi+conv_recu) as total_stats');
$this->db->from('score');
$this->db->where('from_user_id', $user_id);
$result = $this->db->get()->row_array();
print_r($result);
You will get your result
I am trying to add a user to a group. I can run this PHP code without any errors, but the user group is still not changed.
<?php
define('_JEXEC', 1);
define('JPATH_BASE', realpath(dirname(__FILE__)));
require_once ( JPATH_BASE .'/includes/defines.php' );
require_once ( JPATH_BASE .'/includes/framework.php' );
require_once ( JPATH_BASE .'/libraries/joomla/factory.php' );
$userId = 358;
$groupId = 11;
echo JUserHelper::addUserToGroup($userId, $groupId);
?>
I run in the same issue with payment callback. I found that user groups save in the database correctly, but are not refreshed in Juser object (becouse You add user to group in different session). When user interacts on a page groups are restored.
Another think that i found is that changing groups in administrator panel works the same way if user is logged in.
To deal with it I made system plugin and in onAfterInitialise function i do:
//get user
$me = JFactory::getUser();
//check if user is logged in
if($me->id){
//get groups
$groups = JUserHelper::getUserGroups($me->id);
//check if current user object has right groups
if($me->groups != $groups){
//if not update groups and clear session access levels
$me->groups = $groups;
$me->set('_authLevels', null);
}
}
Hope it will help.
Possible "Easy" Solution:
The code is correct and it should put your $userId and $groupId in the db to be precise in #__user_usergroup_map .
Btw consider that this method is rising an error if you use a wrong groupId but it's not raising any error if you insert a wrong $userId and for wrong I mean that it doesn't exist.
So there are canches that the user with $userId = 358; doesn't exist.
Update - Hard Debugging:
Ok in this case I suggest you to digg in the code of the helper.
The file is :
libraries/joomla/user/helper.php
On line 33 You have JUserHelper::addUserToGroup.
This is the code:
public static function addUserToGroup($userId, $groupId)
{
// Get the user object.
$user = new JUser((int) $userId);
// Add the user to the group if necessary.
if (!in_array($groupId, $user->groups))
{
// Get the title of the group.
$db = JFactory::getDbo();
$query = $db->getQuery(true)
->select($db->quoteName('title'))
->from($db->quoteName('#__usergroups'))
->where($db->quoteName('id') . ' = ' . (int) $groupId);
$db->setQuery($query);
$title = $db->loadResult();
// If the group does not exist, return an exception.
if (!$title)
{
throw new RuntimeException('Access Usergroup Invalid');
}
// Add the group data to the user object.
$user->groups[$title] = $groupId;
// Store the user object.
$user->save();
}
if (session_id())
{
// Set the group data for any preloaded user objects.
$temp = JFactory::getUser((int) $userId);
$temp->groups = $user->groups;
// Set the group data for the user object in the session.
$temp = JFactory::getUser();
if ($temp->id == $userId)
{
$temp->groups = $user->groups;
}
}
return true;
}
The bit that save the group is $user->save();.
Try to var_dump() till there and see where is the issue.
Author already halfish solved this problem so this answer may help to others. It took me hours of debugging with Eclipse and XDebug to find the issue. This error was very tricky because addUserToGroup() was returning true for me and user object was as well with successful changes, but they were not saved in database. The problem was that onUserBeforeSave() method in my plugin was throwing exception whenever addUserToGroup() was trying to save a user. So check your implementation of onUserBeforeSave() if you touched it. If not you must install Eclipse with XDebug and try to debug what is your exact problem.
I am using codeigniter pagination class and am stuck in this code!
the following code reads the whole columns from the employees table but my query contains a join. I do not really know how I am going to run my own query using the config settings!
$config['per_page'] = 20;
$view_data['view_data'] = $this->db->get('employees', $config['per_page'], $this->uri->segment(3));
My own query:
$this->db->select('emp.code as emp_code,emp.fname as emp_fname,emp.lname as emp_lname,emp.faname as emp_faname,emp.awcc_phone as emp_phone,emp.awcc_email as emp_email,position as position,dep.title as department');
$this->db->from('employees as emp');
$this->db->join('departments as dep','dep.code=emp.department_code');
$this->db->where('emp.status = 1');
$employees_list = $this->db->get();
return $employees_list;
You approach is totally wrong.
In Controller do it like this
$this->load->model('mymodel');
$config['per_page'] = 20;
$view_data['view_data'] = $this->mymodel->getEmployees($config['per_page'], $this->uri->segment(3));
Modle function
function getEmployees($limit = 10 , $offset = 0)
{
$select = array(
'emp.code as emp_code',
'emp.fname as emp_fname',
'emp.lname as emp_lname',
'emp.faname as emp_faname',
'emp.awcc_phone as emp_phone',
'emp.awcc_email as emp_email',
'position as position',
'dep.title as department'
);
$this->db->select($select);
$this->db->from('employees as emp');
$this->db->join('departments as dep','dep.code=emp.department_code');
$this->db->where('emp.status',1);
$this->db->limit($offset , $limit);
return $this->db->get()->result();
}
See this tutorial for usage
I have successfully created pagination on some of the pages on the application on which I am working with, but I can't make it on this one:
I have 7 records in the database, and when
page is displayed all 7 records are displayed instead of 5, as I would like to be.
Sure enough, links for the paging are not displayed.
Here is my controller code:
public function displayAllFaqCategories()
{
//initializing & configuring paging
$currentUser = $this->isLoggedIn();
$this->load->model('faqCategoriesModel');
$this->db->order_by('sorder');
$limit = 5;
$offset = 3;
$offset = $this->uri->segment(3);
$this->db->limit(5, $offset);
$data['faq_categories'] = $this->faqCategoriesModel->selectCategoriesAndParents();
$totalresults = $this->db->get('faq_categories')->num_rows();
//initializing & configuring paging
$this->load->library('pagination');
$config['base_url'] = site_url('/backOfficeUsers/faqcategories');
$config['total_rows'] = $totalresults;
$config['per_page'] = 5;
$config['uri_segment'] = 3;
$this->pagination->initialize($config);
$errorMessage = '';
$data['main_content'] = 'faq/faqcategories';
$data['title'] = 'FAQ Categories';
$this->load->vars($data,$errorMessage);
$this->load->vars($currentUser);
$this->load->view('backOffice/template');
} // end of function displayAllFaqCategories
And here is my model function code:
public function selectCategoriesAndParents($selectWhat = array())
{
$data = array();
$query = $this->db->query("SELECT fq . * , COALESCE( fqp.$this->parent_name, '0' ) AS parentname
FROM $this->table_name AS fq
LEFT OUTER JOIN $this->table_name AS fqp ON fqp.catid = fq.parentid");
if($query->num_rows() > 0)
{
foreach($query->result_array() as $row)
{
$data[] = $row;
}
}
$query->free_result();
return $data;
} // end of function selectCategoriesAndParents
In the view, bellow of the table with the records I have the following code:
<?php echo $this->pagination->create_links();?>
Any help will be deeply appreciated.
Regards,Zoran
You've mixed two different things together I think. You're partially using the ActiveRecord class of CI, but then running the query yourself.
The simplest change would be:
// get all the rows
$data['faq_categories'] = $this->faqCategoriesModel->selectCategoriesAndParents();
// figure out the count of all of them
$totalresults = count($data['faq_categories']);
// only take some of the rows of the array, instead of keeping all of them and then showing all 7 of your records
$data['faq_categories'] = array_splice($data['faq_categories'], $offset, $limit);
Hopefully that should fix it!
To further explain what the original problem is, I think when you run this:
$totalresults = $this->db->get('faq_categories')->num_rows();
It takes the previous line $this->db->limit(5, $offset); into account, so it only returns 5 rows. Then, when you tell the pagination library that you only want to show 5 per page, the library thinks that it is actually showing all the results, so there is no need for pagination links!
Edit like this
$offset = $this->uri->segment(3) ? $this->uri->segment(3) : 0;
Okay, I am pretty new in CI and I am stuck on pagination. I am performing this pagination on a record set that is result of a query. Now everything seems to be working fine. But there's some problem probably with the link. I am displaying 10 results per page. Now if the results are less than 10 then it's fine. Or If I pull up the entire records in the table it works fine. But in case the result is more than 10 rows, then the first 10 is perfectly displayed, and when I click on the pagination link to get to the next page the next page displays the rest of the results from the query as well as, other records in the table. ??? I am confused.. Any help??
Here's the model code I am using ....
function getTeesLike($field,$param)
{
$this->db->like($field,$param);
$this->db->limit(10, $this->uri->segment(3));
$query=$this->db->get('shirt');
if($query->num_rows()>0){
return $query->result_array();
}
}
function getNumTeesfromQ($field,$param)
{
$this->db->like($field,$param);
$query=$this->db->get('shirt');
return $query->num_rows();
}
And here's the controller code ....
$KW=$this->input->post('searchstr');
$this->load->library('pagination');
$config['base_url']='http://localhost/cit/index.php/tees/show/';
$config['total_rows']=$this->T->getNumTeesfromQ('Title',$KW);
$config['per_page']='10';
$this->pagination->initialize($config);
$data['tees']=$this->T->getTeesLike('Title',$KW);
$data['title']='Displaying Tees data';
$data['header']='Tees List';
$data['links']=$this->pagination->create_links();
$this->load->view('tee_res', $data);
What am I doing wrong here ???? Pls help ...
I guess the problem is with the $KW=$this->input->post('searchstr'); ..
Because if I hard code a value for $KW it works fine. May be I should use POST differently ..but how do I pass the value from the form without POSTING it , its CI so not GET ... ??????
In Controller
<?php
$KW=$this->input->post('searchstr');
$this->load->library('pagination');
$count = $this->model_name->getNumTeesfromQ($KW);//Count
$config['base_url']= base_url().'index.php/tees/show/';
$config['total_rows']= $count;
$config['per_page']='10';
$config['uri_segment'] = 4;
$limit = $config['per_page'];
$this->pagination->initialize($config);
$page = ($this->uri->segment(4)) ? $this->uri->segment(4) : 0;
$data['links'] = $this->pagination->create_links();
$data['tees']=$this->model_name->getTeesLike($KW,$limit,$page);
$data['title']='Displaying Tees data';
$data['header']='Tees List';
$this->load->view('tee_res', $data);
In Model
public function getNumTeesfromQ($KW)
{
$query = $this->db->query("SELECT * FROM title WHERE table_field='$KW'");
$result = $query->result_array();
$count = count($result);
return $count;
}
public function getTeesLike($KW,$limit,$page)
{
$query = $this->db->query("SELECT * FROM title WHERE table_field='$KW' LIMIT $page, $limit");
$result = $query->result_array();
return $result;
}
in view
echo all data using foreach
then at bottom of page use <?php echo $links; ?>this will show your Pagination