I have these two functions below
public function get_posts() {
$this->db->select('p.post_id, p.reply_id, p.user_id, u.username');
$this->db->from('post as p');
$this->db->join('user as u', 'u.user_id = p.user_id');
$this->db->where('p.post_id', $this->input->get('post_id'));
$this->db->or_where('p.reply_id', $this->input->get('post_id'));
// $this->db->group_by('p.user_id');
$query = $this->db->get();
return $query->result_array();
}
Results Output
SELECT * FROM `post` WHERE `post_id` = '1' AND `reply_id` = '0' AND `user_id` = '2'
SELECT * FROM `post` WHERE `post_id` = '3' AND `reply_id` = '1' AND `user_id` = '1'
SELECT * FROM `post` WHERE `post_id` = '5' AND `reply_id` = '1' AND `user_id` = '1'
Total Posts Function
public function total_posts_by_user($user_id, $reply_id, $post_id) {
$this->db->from('post');
$this->db->where('post_id', $post_id);
$this->db->where('reply_id', $reply_id);
$this->db->where('user_id', $user_id);
// $this->db->group_by('user_id');
$query = $this->db->get();
if ($query->num_rows() > 0) {
return $query->num_rows();
}
}
The total_posts_by user gets the number of post shown in image below
Question As you can see there are 2 admin row results showing. But I
would like them to be combined so it will just say row for admin and 2
posts.
I have tried using group_by() on get_post but dos not work
Controller
<?php
class Who_replied extends MX_Controller {
public function __construct() {
parent::__construct();
}
public function index() {
$data['posts'] = array();
$results = $this->get_posts();
foreach ($results as $result) {
$data['posts'][] = array(
'username' => $result['username'],
'total' => $this->total_posts_by_user($result['user_id'], $result['reply_id'], $result['post_id'])
);
$this->total_posts_by_user($result['user_id'], $result['reply_id'], $result['post_id']);
echo $this->db->last_query() . '</br>';
}
$data['total_posts'] = $this->total_posts();
return $this->load->view('default/template/forum/categories/who_replied_view', $data);
}
}
Use left join in first method because current it is using inner join. After that use group by
public function get_posts() {
$this->db->select('p.post_id, p.reply_id, p.user_id, u.username');
$this->db->from('post as p');
$this->db->join('user as u', 'u.user_id = p.user_id','left');
$this->db->where('p.post_id', $this->input->get('post_id'));
$this->db->or_where('p.reply_id', $this->input->get('post_id'));
$this->db->group_by('p.post_id');
$query = $this->db->get();
return $query->result_array();
}
and try. If still face same issue double check whether there are same TWO username admin
** Have you tried DISCTINCT?
hope it will help
I have found my solution from here using COUNT(p.user_id) AS total
public function get_posts() {
$this->db->select('p.post_id, p.reply_id, p.user_id, u.username COUNT(p.user_id) AS total');
$this->db->from('post as p');
$this->db->join('user as u', 'u.user_id = p.user_id');
$this->db->where('p.post_id', $this->input->get('post_id'));
$this->db->or_where('p.reply_id', $this->input->get('post_id'));
$this->db->group_by('p.user_id');
$query = $this->db->get();
return $query->result_array();
}
Related
I have composed a query using Codeigniter's Query Builder class. The query utilizes aliases and the having method. When I call the count_all_results method on this query, an exception occurs. Inspecting the log, I see that the query has stripped out the 'having' clauses. Is there a way to keep these clauses in while calling count_all_results? Thanks for your help.
EDIT: I first believed the problem was knowledge-based and not code-based and so did not share the code, but here it is. Please let me know if more is needed.
Here's the call on the model in the controller.
$where_array = array(
$parent_key.' is not NULL' => null
);
$search_post = $request_data['search'];
if (isset($request_data['filter'])) {
$filter_array = $request_data['filter'];
foreach ($filter_array as $filter_pair) {
if (isset($filter_pair['escape'])) {
$where_array[$filter_pair['filterBy']] = null;
} else {
if ($filter_pair['filterBy'] == 'table3_id') {
$where_array['table3.'.$filter_pair['filterBy']] = isset($filter_pair['filterId']) ?
$filter_pair['filterId'] : null;
} else {
$where_array[$table.'.'.$filter_pair['filterBy']] = isset($filter_pair['filterId']) ?
$filter_pair['filterId'] : null;
}
}
}
}
$like_array = array();
foreach ($request_data['columns'] as $key => $column) {
if (!empty($column['search']['value'])) {
$like_array[$column['data']] = $column['search']['value'];
}
}
$totalFiltered = $this->$model_name->modelSearchCount($search, $where_array, $like_array);
Here's the model methods.
public function modelSearchCount($search, $where_array = null, $like_array = null)
{
$this->joinLookups(null, $search);
if ($where_array) {
$this->db->where($where_array);
}
if ($like_array) {
foreach($like_array as $key => $value) {
$this->db->having($key." LIKE '%". $value. "%'");
}
}
return $this->db->from($this->table)->count_all_results();
}
protected function joinLookups($display_config = null, $search = null)
{
$select_array = null;
$join_array = array();
$search_column_array = $search ? array() : null;
$i = 'a';
$config = $display_config ? $display_config : $this->getIndexConfig();
foreach ($config as $column) {
if (array_key_exists($column['field'], $this->lookups)) {
$guest_model_name = $this->lookups[$column['field']];
$this->load->model($guest_model_name);
$join_string =$this->table.'.'.$column['field'].'='.$i.'.'.
$this->$guest_model_name->getKey();
$guest_display = $this->$guest_model_name->getDisplay();
if ($search) {
$search_column_array[] = $i.'.'.$guest_display;
}
$join_array[$this->$guest_model_name->getTable().' as '.$i] = $join_string;
$select_array[] = $i.'.'.
$guest_display;
} else {
$select_array[] = $this->table.'.'.$column['field'];
if ($search) {
$search_column_array[] = $this->table.'.'.$column['field'];
}
}
$i++;
}
$select_array[] = $this->table.'.'.$this->key;
foreach ($join_array as $key => $value) {
$this->db->join($key, $value, 'LEFT');
}
$this->db->join('table2', $this->table.'.table2_id=table2.table2_id', 'LEFT')
->join('table3', 'table2.table3_id=table3.table3_id', 'LEFT')
->join('table4', $this->table.'.table4_id=table4_id', 'LEFT')
->join('table5', 'table4.table5_id=table5.table5_id', 'LEFT');
$this->db->select(implode($select_array, ', '));
if ($search) {
foreach (explode(' ', $search) as $term) {
$this->db->group_start();
$this->db->or_like($this->table.'.'.$this->key, $term);
foreach ($search_column_array as $search_column) {
$this->db->or_like($search_column, $term);
}
$this->db->group_end();
}
}
$this->db->select('table2_date, '. $this->table.'.table2_id, table4_id, '. 'table5.table5_description');
}
Since count_all_results() will basically run a Select count(*) and not count the rows in your resultset (basically rendering the query useless for your purposes) you may use other Codeigniter methods to get the resultset and the row count.
Try running the query into a variable:
$query = $this->db->get();
From then, you can do pretty much anything. Besides returning the result with $query->result(); you can get the number of rows into another variable with:
$rownum = $query->num_rows();
You can then return that into your controller or even just return the $query object and then run the num_rows() method on the controller
To answer this question, count_all_results() transforms the original query by replacing your selects with SELECT COUNT(*) FROM table. the aliased column would not be selected, and the having clause would not recognize the column. This is why count_all_results() does not work with having.
I have to lots of paginations one lot is for my user's results and the other is for my question results.
When I am on link 3 on my question results it also switches the results on users list pagination.
Question if I click on the questions pagination links how can I make sure it does not affect the results of the user's list.
I have tried this Best way to do multiple pagination on one page in codeigniter does not work
As you can see in image below because I am on questions list page 3 it has effected the users list
<?php
class Dashboard extends MY_Controller {
public $data = array();
public function __construct() {
parent::__construct();
$this->load->model('user/user_model');
$this->load->model('forum/question_model');
$this->load->library('pagination');
}
public function index() {
$this->data['title'] = 'Dashboard';
$this->data['is_logged'] = $this->session->userdata('is_logged');
$config1['base_url'] = base_url('dashboard/');
$config1['total_rows'] = $this->user_model->total_users();
$config1['per_page'] = 2;
$config1['uri_segment'] = 2;
$config1['num_links'] = 200;
$config1['use_page_numbers'] = FALSE;
$config1['prefix'] = 'u_';
$pagination1 = new CI_Pagination();
$pagination1->initialize($config1);
$this->data['pagination1'] = $pagination1->create_links();
$page_segment1 = explode('_', $this->uri->segment(2));
$page1 = ($this->uri->segment(2)) ? $page_segment1[1] : 0;
$this->data['users'] = array();
$users = $this->user_model->get_users($config1['per_page'], $page1);
foreach ($users as $user) {
$this->data['users'][] = array(
'user_id' => $user['user_id'],
'username' => $user['username'],
'status' => ($user['status']) ? 'Enabled' : 'Disabled',
'warning' => '0' . '%',
'date' => date('d-m-Y H:i:s A', $user['date_created_on']),
'href' => site_url('user/profile/') . $user['user_id']
);
}
// Questions Pagination & Results
$config2['base_url'] = base_url('dashboard/');
$config2['total_rows'] = $this->question_model->total_questions();
$config2['per_page'] = 2;
$config2['uri_segment'] = 2;
$config2['num_links'] = 200;
$config2['use_page_numbers'] = FALSE;
$config2['prefix'] = 'q_';
$pagination2 = new CI_Pagination();
$pagination2->initialize($config2);
$this->data['pagination2'] = $pagination2->create_links();
$page_segment2 = explode('_', $this->uri->segment(2));
$page2 = ($this->uri->segment(2)) ? $page_segment2[1] : 0;
$this->data['questions'] = array();
$questions = $this->question_model->get_questions($config2['per_page'], $page2);
foreach ($questions as $question) {
$this->data['questions'][] = array(
'user_id' => $question['user_id'],
'title' => $question['title']
);
}
$this->data['navbar'] = $this->load->view('common/navbar', $this->data, TRUE);
$this->data['header'] = $this->load->view('common/header', $this->data, TRUE);
$this->data['footer'] = $this->load->view('common/footer', '', TRUE);
$this->load->view('common/dashboard', $this->data);
}
}
Question Model
<?php
class Question_model extends CI_Model {
public function get_questions($limit, $start) {
$this->db->select('*');
$this->db->from('questions q');
$this->db->join('users u', 'u.user_id = q.user_id', 'left');
$this->db->limit($limit, $start);
$query = $this->db->get();
return $query->result_array();
}
public function total_questions() {
return $this->db->count_all("questions");
}
}
Users Model
<?php
class User_model extends CI_Model {
public function get_users($limit, $start) {
$this->db->select('u.status, u.date_created_on, ud.*');
$this->db->from('users u', 'left');
$this->db->join('users_userdata ud', 'ud.user_id = u.user_id', 'left');
$this->db->limit($limit, $start);
$query = $this->db->get();
return $query->result_array();
}
public function total_users() {
return $this->db->count_all("users");
}
}
This my controller function
public function update_monthly() {
$data = $this->student_model->get_due_info();
foreach ($data as $value) {
$due = $this->student_model->get_due_by_id($value);
$grade = $this->student_model->get_grade_by_id($value);
$grade_due = $this->student_model->get_due_by_grade($grade);
$new_due = $due + $grade_due;
$this->db->set('md_due',$new_due, FALSE);
}
}
I am getting following error
A PHP Error was encountered
Severity: Notice
Message: Array to string conversion
Filename: database/DB_active_rec.php
Line Number: 427
and
A Database Error Occurred
Error Number: 1054
Unknown column 'Array' in 'where clause'
SELECT `md_due` FROM (`monthly_due`) WHERE `md_student_id` = Array
Filename: F:\xampp\htdocs\student\system\database\DB_driver.php
Line Number: 330
Model Code
public function get_due_by_id($id) {
$this->db->select('md_due');
$this->db->from('monthly_due');
$this->db->where('md_student_id', $id);
$query = $this->db->get();
return $query->result_array();
}
public function get_due_by_grade($id) {
$this->db->select('dt_fee');
$this->db->from('due_table');
$this->db->where('dt_grade', $id);
$query = $this->db->get();
return $query->result_array();
}
public function get_grade_by_id($id) {
$this->db->select('grade');
$this->db->from('student_info');
$this->db->where('student_gen_id', $id);
$query = $this->db->get();
return $query->result_array();
}
public function get_due_info() {
$this->db->select('md_student_id');
$this->db->from('monthly_due');
$query = $this->db->get();
return $query->result_array();
}
Pass $value['md_student_id'] to the model instead of $value in controller.
$data = $this->student_model->get_due_info();
foreach ($data as $value) {
$due = $this->student_model->get_due_by_id($value['md_student_id'] );
$grade = $this->student_model->get_grade_by_id($value['md_student_id']);
$grade_due = $this->student_model->get_due_by_grade($grade[0]['grade']);
//Add remaining logic
}
you are passing whole the array to your model not just the value you want
$due = $this->student_model->get_due_by_id($value);
the right thing is to pass
$value['md_student_id']
this is the value you actually want to pass
replace your code with this
foreach ($data as $value) {
$due = $this->student_model->get_due_by_id($value['md_student_id'] );
$grade = $this->student_model->get_grade_by_id($value['md_student_id']);
$grade_due = $this->student_model->get_due_by_grade($grade[0]['grade']);
$new_due = $due + $grade_due;
$this->db->set('md_due',$new_due, FALSE);
}
I want to add pagination to my component, i've created a simple model with query. I must be missing something. What else do I need here ?
MODEL
jimport('joomla.application.component.modellist');
class PaieskaModelPradinis extends JModelList
{
public function getListQuery()
{
$db = JFactory::getDBO();
$query = "SELECT * FROM #__content";
$db->setQuery( $query );
$db->query( $query );
$result = $db->LoadObjectList();
return $result;
}
}
VIEW
jimport( 'joomla.application.component.view');
class PaieskaViewPradinis extends JView
{
protected $items;
protected $pagination;
function display ($tpl = null)
{
$this->items = $this->get('ListQuery');
$this->pagination = $this->get('Pagination');
parent::display($tpl);
}
}
TPL
foreach ($this->items as $item) {
echo $item->title;
}
EDITED:
I edited a bit code, so now it works fine, almost. Button display(number of rows to display) is not working. And I wonder if this part can be done in a different way ?
$limit = JRequest::getVar('limit' , 25);
$start = JRequest::getVar('start' , 0);
$query = "SELECT * FROM #__content LIMIT $start, $limit";
-
class PaieskaModelPradinis extends JModelList
{
public function getItems()
{
$db = JFactory::getDBO();
$limit = JRequest::getVar('limit' , 25);
$start = JRequest::getVar('start' , 0);
$query = "SELECT * FROM #__content LIMIT $start, $limit";
$db->setQuery( $query );
$db->query( $query );
$lists = $db->LoadObjectList();
return $lists;
}
function getPagination()
{
$main = JFactory::getApplication();
$db = JFactory::getDBO();
$limit = JRequest::getVar('limit' , 25);
$limitstart = JRequest::getVar('limitstart', 0);
$query = "SELECT count(title) FROM #__content";
$db->setQuery( $query );
$total = $db->loadResult();
// include a pagination library
jimport('joomla.html.pagination');
$pagination = new JPagination($total, $limitstart, $limit);
return $pagination;
}
}
VIEW
jimport( 'joomla.application.component.view');
class PaieskaViewPradinis extends JView
{
function display($tpl = null)
{
$this->items = $this->get('items');
$this->pagination = $this->get('pagination');
parent::display($tpl);
}
}
Going off your original code, not the edited version.
The getListQuery method only builds your database query, so you don't execute your query here. Use com_weblinks as an example for building out your model: https://github.com/joomla/joomla-cms/blob/2.5.x/components/com_weblinks/models/category.php
follow this link http://docs.joomla.org/J1.5:Using_JPagination_in_your_component properly.
I have used Joomla pagination. You'll be able to use Joomla pagination easily, if you follow documentation properly. BTW its very simple.
how to show data from 3 tables in one view, because using JTable i can show data only bind to that JTable, please help me with this one.
my code so far(not working) in models:
public function getEntireProject(){
$item_id = $this->getItem()->id;
$db =& JFactory::getDBO();
$query = $db->getQuery(true);
$query->select('*');
$query->from('#__project_part_1 AS a');
$query->leftJoin('#__project_part_2 AS u ON a.uuid = u.uuid');
$query->leftJoin('#__project_part_3 AS y ON a.uuid = y.uuid');
$query->where('a.id = '. (int) $item_id);
$db->setQuery($query);
return $db->loadResult();
}
protected function loadFormData()
{
// Check the session for previously entered form data.
$data = JFactory::getApplication()->getUserState('com_web_projects.edit.webproject.data', array());
if (empty($data)) {
$data = $this->getEntireProject();
}
return $data;
}
try to overwrite getItem function.This will also be helpful if you are calling get('Item') in view. -
public function getItem($pk = null){
if ($item = parent::getItem($pk)) {
$db =& JFactory::getDBO();
$query = $db->getQuery(true);
$query->select('*');
$query->from('#__project_part_1 AS a');
$query->leftJoin('#__project_part_2 AS u ON a.uuid = u.uuid');
$query->leftJoin('#__project_part_3 AS y ON a.uuid = y.uuid');
$query->where('a.id = '. (int) $item->id);
$db->setQuery($query);
$item = $db->loadAssoc();
}
return $item;
}
protected function loadFormData()
{
// Check the session for previously entered form data.
$data = JFactory::getApplication()->getUserState('com_web_projects.edit.webproject.data', array());
if (empty($data)) {
$data = $this->getItem();
}
return $data;
}
For Multi-Row Results use loadRowList(), loadAssocList(), loadAssocList($key), loadObjectList(), loadObjectList('key'). $db->loadResult() only load one result. Read more.
If I understand your question right this should fix your problem. If you not please ask.