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
Related
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");
I wanted to display multiple column values from my database.
Using the query from model
$this->db->select('*');
$this->db->from('projectskillslist ps');
$this->db->join('empskillslist s', 's.skillsID = ps.skillsID', 'left');
$this->db->join('projects p', 'p.projectID = ps.projectID', 'left');
$this->db->where('ps.projectID = 1');
$query = $this->db->get();
$result = $query->result_array();
if ($query->num_rows() > 0) {
return $result;
}
return false;
And in my controller
$data['pSkills'] = $this->emp_model->view_projskills();
The query returns perfectly as expected:
Now in my view,
I wanted to call
Title: Project 1
SkillName: JAVA, PHP
So far, I have done this:
foreach ($pSkills as $data) {
echo $data['title'];
echo $data['skillName'];
}
And the result I am getting is
Title: Project 1
Skills: PHP
Title: Project 2
Skills: JAVA
It is a silly question indeed, I have already looked up and search for the same problem but I still no luck. I hope you can help me. Thank you so much!!
Try this, but first order the result set by Project ID and Skill ID.
$this->db->order_by('projectID, skillID');
view
$lastProjectID = 0;
$p_skills = '';
$p_title = '';
foreach ($pSkills as $data) {
if ($data['projectID'] !== $lastProjectID) {
// if there's a title, printIt()
if ($p_title !== '') {
printIt($p_title, $p_skills);
}
// set new title and skill list
$p_title = $data['title'];
$p_skills = $data['skillName'];
// remember last project
$lastProjectID = $data['projectID'];
} else {
// append skill name to skills
$p_skills .= ", " . $data['skillName'];
}
}
// end of foreach, if there's a title, printIt()
if ($p_title !== '') {
printIt($p_title, $p_skills);
}
function printIt($title, $skills) {
echo "Title: $title<br>";
echo "SkillName: $skills<br>";
}
Follow these step if it would can help..
Step 1: You have to concatenate projectID where GROUP_CONCAT will help.
Step 2. Perform your SQL query like below
SELECT projectID, skillName, GROUP_CONCAT(projectID) AS projid FROM
projectskillslist GROUP BY projid
Step 3: To display it in a view , you can use PHP's explode() and iterate over that, like this if it would help..
foreach ($pSkills as $row) {
echo $row->title;
echo explode(',', $row->skillName);
/*
or add below line of code if it doesn't works
*/
//echo str_replace(',', '<br />', $row->skillName);
}
I am taking data from many tables. I want to display many objects in different places. I got the data from data base, but I want to put the data into an array for useful purpose, but it's not working.
This my controller code:
public function compare_by_business_sectors() {
//print_r($this->input->post());exit;
if ($this->input->post())
{
$solution_array = array();
//print_r (json_encode($business_sectors)); exit;
$business_sectors=$this->home_model->compare_business_sectors_data($this->input->post());
$tab_child_id = "";
$id="";
foreach ($business_sectors as $key=>$sectors) {
$solution_array[1]=$sectors->solution_name;
$solution_array[2]=$sectors->description;
$solution_array[3]=$sectors->vendor_name;
$solution_array[4]=$sectors->video_presentation;
$solution_array[5]=$sectors->start_free_trail;
$solution_array[6]=$sectors->hardware_package;
$solution_array[7]=$sectors->pos_market_rating;
//$solution_array[$sectors->field_id] = $sectors->value;
$id = "solution".$sectors->tab_child_id;
if ($tab_child_id != $sectors->tab_child_id) {
$id = array();
$id[$sectors->field_id] = $sectors->title;
}
else if ($tab_child_id == $sectors->tab_child_id) {
$id[$sectors->field_id] = $sectors->title;
}
}
//$solution_array[$id]= $id;
}
print_r($id);
//$this->load->view('compare_by_business_sectors.php');
}
This is my model code:
public function compare_business_sectors_data($sectorid) {
$query = $this->db->select('solutions.*,solution_tabs_child_fields.field_id,solution_tabs_child_fields.tab_child_id,solution_tabs_child_fields.title')
->from('solutions')
//->join('solutions', 'business_sector.sector_id = solutions.business_sector_id',"left")
->join('solution_features','solutions.entry_id = solution_features.entry_id',"left")
->join('solution_tabs_child_fields','solution_features.field_id = solution_tabs_child_fields.field_id')
->where('solutions.business_sector_id', $sectorid['id'])
->get();
return $query->result();
//print_r($query->result());exit;
}
change it as follow and try.
$id_string = "";
$id_array = array();
foreach ($business_sectors as $key=>$sectors) {
$solution_array[1]=$sectors->solution_name;
$solution_array[2]=$sectors->description;
$solution_array[3]=$sectors->vendor_name;
$solution_array[4]=$sectors->video_presentation;
$solution_array[5]=$sectors->start_free_trail;
$solution_array[6]=$sectors->hardware_package;
$solution_array[7]=$sectors->pos_market_rating;
//$solution_array[$sectors->field_id] = $sectors->value;
$id_string = "solution".$sectors->tab_child_id;
if ($tab_child_id != $sectors->tab_child_id) {
$id[$sectors->field_id] = $sectors->title;
}
else if ($tab_child_id == $sectors->tab_child_id) {
$id[$sectors->field_id] = $sectors->title;
}
}
print_r($id_string);
print_r($id_array);
First you are assigning string value to $id then, $id will convert to array only if first if() statement execute other wise it will not be a string. So to overcome from this keep $id_array before for loop and you can capture string in another variable.
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 have a problem in a class I can't solve, the loop breaks in getAlojamiento() when I call getImagenes() inside the while. In this case getAlojamiento() returns only one row, it should return all the rows. Here are the methods involved:
//THIS GETS THE ROWS FROM A TABLE AND RETURN AN ARRAY, IF $id IS SET, CHECKS IF id_asoc == $id
public function getImagenes($table, $id=false){
$return = '';
//checks if id id == true
if($id){
$sql="SELECT * FROM $table WHERE id_asoc = '$id' ORDER BY id DESC";
}else{
$id = '';
$sql="SELECT * FROM $table ORDER BY id DESC";
}
//this make the sql request (returns an array)
if(!$this->MySQLQuery($sql)){
$return = false;
}else{
if($this->dbNumberRows == 0){ //cheks if there are results
$return = false;
}else{ //if has results makes and fills an array
$items = array();
while($f = mysql_fetch_object($this->dbResults)){
$items[$f->id]['id'] = $f->id;
$items[$f->id]['id_asoc'] = $f->id_asoc;
$items[$f->id]['comentario'] = htmlentities($f->comentario);
$items[$f->id]['nombre'] = htmlentities($f->nombre);
}
$return = $items;
}
}
return $return;
}
//THIS GETS THE ROWS FROM A TABLE AND RETURN AN ARRAY
public function getAlojamiento($id=false){
$return = '';
//checks if id id == true
if($id){
$sql="SELECT * FROM tb_alojamiento WHERE id = '$id' LIMIT 1";
}else{
$id = '';
$sql="SELECT * FROM tb_alojamiento ORDER BY titulo ASC";
}
//this make the sql request (returns an array)
if(!$this->MySQLQuery($sql)){
$return = false;
}else{
if($this->dbNumberRows == 0){ //cheks if there are results
$return = false;
}else{ //if has results makes and fills an array
$items = array();
while($f = mysql_fetch_object($this->dbResults)){
$imagenes_arr = $this->getImagenes('tb_alo_imagenes', $f->id); //this is causing the break
$items[$f->id]['id'] = $f->id;
$items[$f->id]['titulo'] = $f->titulo;
$items[$f->id]['telefono'] = $f->telefono;
$items[$f->id]['descripcion'] = $f->descripcion;
$items[$f->id]['email'] = $f->email;
$items[$f->id]['url'] = $f->url;
$items[$f->id]['direccion'] = $f->direccion;
$items[$f->id]['ubicacion'] = $f->ubicacion;
$items[$f->id]['coordenadas'] = $f->coordenadas;
$items[$f->id]['disponibilidad'] = $f->disponibilidad;
$items[$f->id]['tarifas'] = $f->tarifas;
$items[$f->id]['servicios'] = $f->servicios;
$items[$f->id]['theme'] = $f->theme;
$items[$f->id]['premium'] = $f->premium;
$items[$f->id]['img_ppal_id'] = $f->img_ppal_id;
$items[$f->id]['imagenes'] = $imagenes_arr;
}
$return = $items;
}
}
return $return;
}
The problem is that you are using $this->dbResults for both queries. When you call getImagenes you are clobbering the dbResults in getAlojamiento.
A simple solution to avoid having the first mysql query affect other queries is to complete it first:
//first loop over the result set from first query
while($f = mysql_fetch_object($this->dbResults))
{
//note: no call to $this->getImagenes here!
$items[$f->id]['id'] = $f->id;
$items[$f->id]['titulo'] = $f->titulo;
....
}
//only now you fetch the images in a second pass
foreach( $items as $id => $item )
{
$items[$id]['imagenes'] = $this->getImagenes('tb_alo_imagenes', $id);
}
//return the complete $items array
$return = $items;
while($f = mysql_fetch_object($this->dbResults)){
$items[$f->id]['id'] = $f->id;
$items[$f->id]['id_asoc'] = $f->id_asoc;
$items[$f->id]['comentario'] = htmlentities($f->comentario);
$items[$f->id]['nombre'] = htmlentities($f->nombre);
}
$return[] = $items;
You're setting the array to be the single $items array. You need to add it to the $return array.