I have two tables : users ('ID' 'username' '...') and connectivities('ID' 'following_ID' '...')
Each time one user follows another, an entry is created in connectivities. The followers are sorted in descending order after a query by user ID. Now I do not want to sort the followers by ID but by the entries in connectivities. So that always the last new follower is displayed first.
public function getFollowers($offset = false,$limit = null){
if (empty($this->user_id) || !is_numeric($this->user_id)) {
return false;
}
else if (!empty($limit) && !is_numeric($limit)) {
return false;
}
$user_id = $this->user_id;
$t_users = T_USERS;
$t_conn = T_CONNECTIV;
self::$db->join("{$t_conn} c","c.follower_id = u.user_id AND c.type = 1","INNER");
self::$db->where("c.following_id",$user_id);
self::$db->orderBy("u.user_id","DESC");
if (!empty($offset) && is_numeric($offset)) {
self::$db->where("u.user_id",$offset,'<');
}
$users = self::$db->get("{$t_users} u",$limit);
$data = array();
foreach ($users as $key => $user_data) {
$user_data = $this->userData($user_data);
$user_data->is_following = false;
if (IS_LOGGED) {
$this->user_id = self::$me->user_id;
$user_data->is_following = $this->isFollowing($user_data->user_id);
}
$data[] = $user_data;
}
return $data;
}
If I have changed self :: $ db-> orderBy ("u.user_id", "DESC"); to self :: $ db-> orderBy ("c.id", "DESC"); that works as well but always the same ex 20 entries are displayed.
These are then always repeated. I think the problem is the offset.
Does somebody has any idea?
invoke $db->orderBy twice, to sort rows by u.userid desc, c.id desc
self::$db->join("{$t_conn} c","c.follower_id = u.user_id AND c.type = 1","INNER");
self::$db->where("c.following_id",$user_id);
self::$db->orderBy("u.user_id desc","c.id desc");
Related
I'm working on a system that has several server-side datatables but i facing issues with 2 joins when i try to order de columns.
I receive the following message when try to sort the columns:
Query error: Column 'notes' in order clause is ambiguous - Invalid query: SELECT *
FROM `tbl_project`
LEFT JOIN `tbl_client` ON `tbl_project`.`client_id`=`tbl_client`.`client_id`
LEFT JOIN `tbl_account_details` ON `tbl_project`.`created_by` = `tbl_account_details`.`user_id`
LEFT JOIN `tbl_notes` ON `tbl_project`.`notes` = `tbl_notes`.`notes_id`
WHERE `tbl_project`.`client_id` = '100'
ORDER BY `notes` DESC
LIMIT 10
This is the code with my query:
$id = $this->input->post("client_id");
$client_details = get_row('tbl_client', array('client_id' => $id));
$draw = intval($this->input->post("draw"));
$start = intval($this->input->post("start"));
$length = intval($this->input->post("length"));
$order = $this->input->post("order");
$search= $this->input->post("search");
$search = $search['value'];
$col = 0;
$dir = "";
if(!empty($order))
{
foreach($order as $o)
{
$col = $o['column'];
$dir= $o['dir'];
}
}
if($dir != "desc" && $dir != "desc")
{
$dir = "desc";
}
$valid_columns = array(
0=>'project_id',
1=>'client',
2=>'fullname',
3=>'notes',
4=>'origen',
5=>'end_date',
6=>'project_status',
7=>'action',
);
if(!isset($valid_columns[$col]))
{
$order = null;
}
else
{
$order = $valid_columns[$col];
}
if($order !=null)
{
$this->db->order_by($order, $dir);
}
$searchQuery = "";
if($search != ''){
$searchQuery = " (tbl_project.project_id like'%".$search."%' OR tbl_project.end_date like'%".$search."%' OR tbl_project.project_status like'%".$search."%' OR tbl_notes.notes like'%".$search."%' OR tbl_notes.eco like'%".$search."%' OR tbl_account_details.origen like'%".$search."%' OR tbl_client.name like'%".$search."%') ";
}
$this->db->select('*');
$this->db->from('tbl_project');
$this->db->join('tbl_client', 'tbl_project.client_id=tbl_client.client_id','left');
$this->db->join('tbl_account_details', 'tbl_project.created_by = tbl_account_details.user_id','left');
$this->db->join('tbl_notes', 'tbl_project.notes = tbl_notes.notes_id','left');
$this->db->where('tbl_project.client_id', $client_details->client_id);
if($searchQuery != '')
$this->db->where($searchQuery);
$this->db->limit($length,$start);
$cita = $this->db->get()->result();
For some reason the ORDER BY is not set as tbl_notes.notes
Any suggestion on how to fix this?
Thanks in advance
EDIT: i have added more code so there is more visibility of the process
The error occurs, because your column name is not unique, it exists in more than one table.
append the table name of the searched column to your query to make it unique:
for example in this line:
$this->db->order_by('my_table_name.'.$order, $dir);
that would generate something like
ORDER BY `my_table_name.notes` DESC
edit: or in case you have to address columns from several different tables you could change your $valid_columns array:
$valid_columns = array(
0=>'my_table_name1.project_id',
1=>'my_table_name2.client',
2=>'my_table_name2.fullname',
3=>'my_table_name3.notes',
// etc.
);
and maintain the remaining original code.
Im trying get a list of userIds from the videos table. This table contains the media files that get uploaded the users. This is my code
$this->db->select("videos.user_id as userId");
$this->db->limit('10', $document['offset']);
$this->db->group_by('userId');
$this->db->order_by('id','desc');
$recentUploads = $this->db->get('videos')->result_array();
if (!empty($recentUploads))
{
foreach ($recentUploads as $record)
{
$totalPostMedia = $obj->totalPostMedia($record);
$record['totalPostMedia'] = $totalPostMedia;
$resData = $this->db->select("username, profileImage")->from('users')->where('id', $record['userId'])->get()->row_array();
$record['uploadBy'] = $resData['username'];
$record['profileImage'] = "http:...com/profileImage/".$resData['profileImage'];
$Mydata[] = $record;
}
}
The result get is missing some of the userIds from the table. I have tried $this->db->distinct() as well. Still got the same result. The only way i get a result with no duplicates is when i remove $this->db->order_by('id','desc'); or make it asc instead of desc. But i want to get the latest records from the table. how do i do this? Am i doing something wrong? any help would be much appreciated.
try this
$this->db->select("videos.user_id as userId");
$this->db->from("videos");
$this->db->group_by('userId');
$this->db->order_by('id','desc');
$this->db->limit('10', $document['offset']);
$recentUploads = $this->db->get()->result_array();
if (count($recentUploads)>0)
{
foreach ($recentUploads as $record)
{
$totalPostMedia = $obj->totalPostMedia($record);
$record['totalPostMedia'] = $totalPostMedia;
$resData = $this->db->select("username, profileImage")->from('users')->where('id', $record['userId'])->get()->row_array();
$record['uploadBy'] = $resData['username'];
$record['profileImage'] = "http:...com/profileImage/".$resData['profileImage'];
$Mydata[] = $record;
}
}
in your request (i mean select videos.user_id as userId) in the group_by ligne you make userId to do the group by traitement. your userId alias is not knowing as colum name that can do any traitement of it.
for that replace your userId by videos.user_id in your group by ligne.
your code will be like this to work for you
$this->db->select("videos.user_id as userId");
$this->db->limit('10', $document['offset']);
$this->db->group_by('videos.user_id');
$this->db->order_by('id','desc');
$recentUploads = $this->db->get('videos')->result_array();
if (!empty($recentUploads))
{
foreach ($recentUploads as $record)
{
$totalPostMedia = $obj->totalPostMedia($record);
$record['totalPostMedia'] = $totalPostMedia;
$resData = $this->db->select("username, profileImage")->from('users')->where('id', $record['userId'])->get()->row_array();
$record['uploadBy'] = $resData['username'];
$record['profileImage'] = "http:...com/profileImage/".$resData['profileImage'];
$Mydata[] = $record;
}
}
use max(id)
as in $this->db->select("videos.user_id as userId,max(id)");`
so you might try:
$this->db->select("videos.user_id as userId, max(id)");
$this->db->limit('10', $document['offset']);
$this->db->group_by('userId');
$this->db->order_by('id','desc');
$recentUploads = $this->db->get('videos')->result_array();
if (!empty($recentUploads))
{
foreach ($recentUploads as $record)
{
$totalPostMedia = $obj->totalPostMedia($record);
$record['totalPostMedia'] = $totalPostMedia;
$resData = $this->db->select("username, profileImage")->from('users')->where('id', $record['userId'])->get()->row_array();
$record['uploadBy'] = $resData['username'];
$record['profileImage'] = "http:...com/profileImage/".$resData['profileImage'];
$Mydata[] = $record;
}
}
https://stackoverflow.com/a/14770936/1815624
I have 3 tables guest_user_info,pg_company,user_profile.
In guest_user_info have 2 columns:
g_uid | company_id
In pg_company have 2 columns:
company_id | user_id
In user_profile have 2 columns:
id |user_email
Here i want to get user_email from user_profile.i have g_uid value (in guest_user_info table).i want company_id from guest_user_info and get the company_id and match with pg_company table,there i can get user_id.then match with that user_id with id in user_profile table.at last i need user_email from user_profile table
Well its a simple one, you just need to join using active query in CodeIgniter.
$this->db->select("UP.id", "UP.user_email");
$this->db->from("guest_user_info AS GU");
$this->db->join("pg_company AS PC", "PC.company_id=GU.company_id");
$this->db->join("user_profile AS UP", "UP.id=PC.user_id");
$this->db->where("GU.g_uid", $guid);
$query = $this->db->get();
return $query->result();
In above code, $guid you have to provide which you have.
Also please take a look at these links:
https://www.codeigniter.com/userguide3/database/query_builder.html
https://www.codeigniter.com/userguide2/database/active_record.html
You get so many things after reading this.
Check bellow code it`s working fine and common model function also
supported more then one join and also supported multiple where condition
order by ,limit.it`s EASY TO USE and REMOVE CODE REDUNDANCY.
================================================================
*Album.php
//put bellow code in your controller
=================================================================
$album_id='';//album id
//pass join table value in bellow format
$join_str[0]['table'] = 'pg_company';
$join_str[0]['join_table_id'] = 'pg_company.company_id';
$join_str[0]['from_table_id'] = 'guest_user_info.company_id';
$join_str[0]['join_type'] = '';//set join type
$join_str[1]['table'] = 'user_profile';
$join_str[1]['join_table_id'] = 'user_profile.id';
$join_str[1]['from_table_id'] = 'guest_user_info.user_id';
$join_str[1]['join_type'] = '';
$selected ="guest_user_info.*,user_profile.user_name,pg_company.name";
$condition_array=array('guest_user_info.g_uid' => $g_uid);
$albumData= $this->common->select_data_by_condition('guest_user_info', $condition _array, $selected, '', '', '', '', $join_str);
//call common model function
if (!empty($albumData)) {
print_r($albumData); // print album data
}
=========================================================================
Common.php
//put bellow code in your common model file
========================================================================
function select_data_by_condition($tablename, $condition_array = array(), $data = '*', $sortby = '', $orderby = '', $limit = '', $offset = '', $join_str = array()) {
$this->db->select($data);
//if join_str array is not empty then implement the join query
if (!empty($join_str)) {
foreach ($join_str as $join) {
if ($join['join_type'] == '') {
$this->db->join($join['table'], $join['join_table_id'] . '=' . $join['from_table_id']);
} else {
$this->db->join($join['table'], $join['join_table_id'] . '=' . $join['from_table_id'], $join['join_type']);
}
}
}
//condition array pass to where condition
$this->db->where($condition_array);
//Setting Limit for Paging
if ($limit != '' && $offset == 0) {
$this->db->limit($limit);
} else if ($limit != '' && $offset != 0) {
$this->db->limit($limit, $offset);
}
//order by query
if ($sortby != '' && $orderby != '') {
$this->db->order_by($sortby, $orderby);
}
$query = $this->db->get($tablename);
//if limit is empty then returns total count
if ($limit == '') {
$query->num_rows();
}
//if limit is not empty then return result array
return $query->result_array();
}
I have two tables sport_tbl, match_tbl. In sport_tbl, i defined sport_name such as cricket. In match_tbl, I have match_name,match_date,sport_id.
I want to show match_date of every sport_name (ex. i am showing match_date list for cricket sport and i want to show every date has match_name list).
I want to show one distinct match_date.
Image
my controller code:-
$url = 'cricket' // for example first sport_name
$data['getSportMatch'] = $this->user_model->getSportMatch($url);
my model code:-
public function getSportMatch($sport)
{
$query = $this->db->get_where('match_tbl',array('sport_name' => $sport));
if($query->num_rows > 0)
{
foreach($query->result() as $item){
$data[] = $item;
}
return $data;
}
}
my code in view:-
<div><?php foreach($getSport as $item): ?><h4><?= $item->sport_name; ?></h4><div><?= foreach($getSportMatch as $item): ?>
match_date)) ?>here i want to show list match_name of every match_date
My table structure images
1) sport_tbl
2) match_tbl
3) another match_tbl
you can solve this in model easily. if i did not understand wrong . you need 2 function in model.
1. will get sport names
2. will get matches of given sport name
//model functions
function get_sports(){
$data = array();
$sports = $this->db->select('sport_name')->from('sport_tbl')->get()->result();
if($sports)
{
foreach($sports as $sport){
$data[$sport->sport_name] = $this->get_matches($sport->sport_name);
}
return $data;
}
}
function get_matches($sport_name){
$matches = $this->db->select('*')->from('match_tbl')->where('sport_name',$sport_name)->get()->result();
return $matches;
}
so in view data will be something like this
$data => array(
'cricket'=> array(0 => array(
'match_id' => 11,
'sport_id' = 2 .....
)))
Try this coding ...
public function getSportMatch($sport)
{
$query = $this->db->query("SELECT * FROM sport_tbl as st INNER JOIN match_tbl as mt ON st.sport_id = mt.sport_id WHERE st.sport_name ='".$sport."'");
if($query->num_rows > 0)
{
$query_result = $query->result_array();
$final_result = array();
foreach($query_result as $result ) {
$date = $result['match_date'];
$final_result[$date][] = $result;
}
return $final_result;
}
}
View Coding :-
if(isset($final_result)) {
foreach($final_result as $result) {
echo $result['match_date']; // First display match date
if(isset($result['match_date'])) {
foreach($result['match_date'] as $match) {
echo $match['match_name']; // Second listout the match name
}
}
}
}
i first checked if there any same problems like mine i ddnt find anything.
all are sorting alphanumeric column mixed with numeric data.
here is my problem.
i have a table that contain column A datas like this.
WRG-01 WRG-39 WRG-22 WRG-45 WRG-43
need to sort that as
WRG-01 WRG-22 WRG-39 WRG-43 WRG-45
this is the code i using so far in codeigniter frame work
$data['products'] = $this->db->order_by('product_id', 'asc')->get('products');
in mysql i can use this query to get done my work
preg_replace("/[^\d]/", "",'product_id'), 'asc')
How to apply it to my above codeigniter code?
here is search funtion
public function search()
{
$data['title'] = 'Search Product';
$product_name = $this->input->get('product_name');
$product_id = $this->input->get('product_id');
$product_category = $this->input->get('product_category');
$secondCategory = $this->input->get('secondCategory');
$thirdCategory = $this->input->get('thirdCategory');
$data['category'] = $this->db->order_by('id', 'asc')->get_where('categories', ['parent' => 0]);
if($product_category != '')
{
$data['secondCategory'] = $this->db->get_where('categories', ['parent' => $product_category]);
}
if($secondCategory != '')
{
$data['thirdCategory'] = $this->db->get_where('categories', ['parent' => $secondCategory]);
}
if($product_name != '')
{
$this->db->like('product_name', $product_name);
}
if($product_id != '')
{
$this->db->where('product_id', $product_id);
}
if($product_category != '')
{
$this->db->where('product_category', $product_category);
}
if($secondCategory != '')
{
$this->db->where('secondCategory', $secondCategory);
}
if($thirdCategory != '')
{
$this->db->where('thirdCategory', $thirdCategory);
}
$data['products'] = $this->db->order_by('product_id' 'asc')->get('products');
theme('all_product', $data);
}
i can't use sql query here because products is result array from product table.
Use MySQL cast
cast(product_id as SIGNED)
or
cast(product_id as UNSIGNED)
Try query like that :-
select * from products cast(product_id as UNSIGNED) ASC|DESC
Try this
$query= $this->db->query("SELECT * FROM products WHERE ??==?? ORDER BY product_id ASC");
$result= $query->result_array();
return $result;
as default data will sort by Ascending Order
This is in model. So if you pass it to controller it will return data as Objective Array.
So in controller you can access
$result = $this->model_name->method_for_above_code();
$name = $result[0]['name'];
$id = $result[0]['id'];
if in View
$result['this_for_view'] = $this->model_name->method_for_above_code();
foreach ($this_for_view as $new_item) {
echo "Name is ".$new_item['name'];
echo "ID is ".$new_item['id'];
}