I want to get all query results where I get the id's from another query. I get all relevant id's from both table but i can show only one result in my view. Where is my folt, and how can I fix this?
my Controller:
$results = $this->my_model->hd($query_array ,$limit, $offset);
$data['r']= $results ['rows'];
$data['num_results']= $results ['num_rows'];
$id_str = '';
foreach($results['rows'] as $row){
$id_str .= $row->id . ',';
}
$id_str = rtrim($id_str, '');
$doff = $this->my_model->off($id_str);
$data['o']= $doff ['rows'];
My Model:
function hd($query_array,$limit, $offset){
//result query
$q = $this->db->select('*')
->from('a')
->limit($limit, $offset);
if (strlen($query_array['cy'])){
$q->like('cy', $query_array['cy']);
}
if (strlen($query_array['cat'])){
$q->where('cat', $query_array['cat']);
}
if (strlen($query_array['rat'])){
$q->where('rat', $query_array['rat']);
}
$ret['rows'] = $q->get()->result();
$q = $this->db->select('COUNT(*) as count', FALSE)
->from('r');
if (strlen($query_array['cy'])){
$q->like('cy', $query_array['cy']);
}
if (strlen($query_array['cat'])){
$q->where('cat', $query_array['cat']);
}
if (strlen($query_array['rat'])){
$q->where('rat', $query_array['rat']);
}
$tmp = $q->get()->result();
$ret['num_rows'] = $tmp[0]->count;
return $ret;
}
function off($id_str){
$off_a = $this->db->select('*')
->from('off')
->where('r_id', $id_str);
$ret['rows'] = $off_a->get()->result();
return $ret;
}
I show in my view the result in a foreach loop. I tried to fix this problem since three days by my self and google, but no luck.
Related
Using Codeigniter 3, I would like to display all the records from a table in a MySQL database. I'd also like to include the number of records selected.
For example;
Showing x number of records;
record 1
record 2
record 3
etc
Currently I have the following (which works);
// select all records
public function selectRecords() {
$this->db->select('*');
$this->db->from('records');
$query = $this->db->get();
return $query->result_array();
}
// count all records
public function countRecords() {
$this->db->select('count(*) as count');
$this->db->from('records');
$query = $this->db->get();
return $query->row();
}
My question is do I need two separate queries in order to achieve this (select and count)?
Is there a more efficient way of achieving what I want?
You can do something like this :
public function selectRecords()
{
$query = $this->db->get('records');
if ($query->num_rows() > 0 )
{
$records = $query->result_array();
$data['count'] = count($records);
$data['all_records'] = $records;
return $data;
}
}
Pass it to the view from your controller :
$data = $this->model_name->selectRecords();
/*print_r($data) to see the output*/
$this->load->view('your_view',$data);
In view :
<?php echo $count .' number of records';?>
you can do only:
public function selectRecords() {
$this->db->select('*');
$this->db->from('records');
$query = $this->db->get();
return $query->result_array();
}
and
$records = $this->selectRecords();
$count = count($records);
In The first function itself you can get the count using $query->num_rows() function
public function selectRecords() {
$return = array();
$this->db->select('*');
$this->db->from('records');
$query = $this->db->get();
$return['count'] = $query->num_rows();
$return['records'] = $query->result_array();
return $return;
}
try this
it will help you to provide pagination for records
public function selectRecords($params = array(), $count = false) {
$offset = isset($params['offset']) ? $params['offset'] : '';
$limit = isset($params['limit']) ? $params['limit'] : '';
$this->db->select('*');
$this->db->from('records');
$query = $this->db->get();
if ($count) {
return $this->db->get()->num_rows();
}
if (empty($offset) && !empty($limit)) {
$this->db->limit($limit);
}
if (!empty($offset) && !empty($limit)) {
$this->db->limit($limit, $offset);
}
$result = $this->db->get()->result();
return $result;
}
Friends I'm Unable to get open positions Sum. here is my code. I am getting 1(one) instead of total sum. Help me to solve this issue.
Controller:
function index(){
$userId = $this->phpsession->get("userId");
$userType = $this->phpsession->get('userType');
$date = date("Y-m-d");
if(!$userId && !$this->phpsession->get("userType")){
redirect(base_url().'user');
}
$config['base_url'] = base_url().'requirement/index';
$config['total_rows'] = $this->requirement_model->GetRequirement(array("count"=>true));
$config['per_page'] = 5;
$config['cur_tag_open'] = '<a>';
$config['cur_tag_close'] = '</a>';
$this->pagination->initialize($config);
$options['offset'] = $this->uri->segment(3);
$options['limit'] = $config['per_page'];
$options['join']=true;
$data['clients'] = $this->client_model->ajaxclient();
$data['requirements'] = array(""=>"Choose requirement");
$data['requirement'] = $this->requirement_model->GetRequirement($options);
$data['links'] = $this->pagination->create_links();
$data['totalactive']=$this->requirement_model->GetRequirement(array("find"=>true));
$data['totalrequirement']=$this->requirement_model->GetRequirement(array("totalreq"=>true));
$data['openpositions']=$this->requirement_model->GetRequirement(array("openpos"=>true));
//print_R($data['openpositions']);exit;
//echo "<pre>"; print_R($this->db->last_query()); exit;
$data['page_title'] = "Requirement Details";
$this->layout->view("requirement/index",$data);
}
This is my model function
Model:
function GetRequirement($options = array()){
if(isset($options['requirementId']))
$this->db->where('requirementId',$options['requirementId']);
if(isset($options['clientName']))
$this->db->where('clientName',$options['clientName']);
if(isset($options['limit']) && isset($options['offset']))
$this->db->limit($options['limit'], $options['offset']);
else if(isset($options['limit']))
$this->db->limit($options['limit']);
$this->db->order_by("activateddate", "DESC");
if(isset($options['join'])){
$this->db->select('r.*,c.clientName as cName');
$this->db->from('requirement as r');
$this->db->join('clients as c','c.clientId=r.clientName');
$query=$this->db->get();
if(#$options['requirementId']) return $query->row(0);
return $query->result();
}
if(isset($options['find'])){
$this->db->select('distinct(clientName)');
$this->db->from('requirement');
$this->db->where('(clientName) and (noofpositions > 0) ');
$this->db->count_all();
$query=$this->db->get();
return $query->num_rows();
}
if(isset($options['totalreq'])){
$this->db->select('requirementName');
$this->db->from('requirement');
$this->db->where('(noofpositions > 0) ');
$this->db->count_all();
$query=$this->db->get();
return $query->num_rows();
}
if(isset($options['openpos'])){
$this->db->select_sum('openPos');
$this->db->from('requirement');
$this->db->where('(closedPos = 0) ');
$this->db->count_all();
$query=$this->db->get();
return $query->num_rows();
}
$query = $this->db->get('requirement');
if(isset($options['count'])) return $query->num_rows();
if(#$options['requirementId']) return $query->row(0);
return $query->result();
}
This is my View page
View:
<div class="inner">
<h3><?php echo $openpositions; ?></h3>
<p>Total Positions Opened</p>
</div>
You are using sum which is an aggregate function and with out group by it will take whole table as one group in if(isset($options['openpos'])){ ... } part of code of your model your are returning num_rows() which returns the no. of rows so in your case there will be one row with the value of sum therefore you are getting result as 1 change your
if (isset($options['openpos'])) {
$this->db->select_sum('openPos');
$this->db->from('requirement');
$this->db->where('(closedPos = 0) ');
$query = $this->db->get();
return $query->row()->openpos;
}
I think the mysql statement has an error.
Change the following line:
$this->db->where('(closedPos = 0) ');
To
$this->db->where('closedPos', 0);
remove the following line: (this will count all rows and return the value, which you do not want)
$this->db->countall();
If this does not solve your problem you could try outputting the mysql statement by adding exit($this->db->last_query()); to try and find the problem, like this:
if(isset($options['openpos'])){
$this->db->select_sum('openPos');
$this->db->from('requirement');
$this->db->where('(closedPos = 0) ');
$this->db->count_all();
$query=$this->db->get();
// output last query
exit($this->db->last_query());
return $query->num_rows();
}
Is it possible to split queries somehow like this?
public function getStatuses($dates)
{
$query = DB::table('tickets');
if ($dates['from'])
$query = $query->where('from', $dates['from']);
if ($dates['to'])
$query = $query->where('to', $dates['to']);
$query = $query->select('Active');
return $query->get()->toArray();
}
Yes, it's possibile. But don't reassign to the same variable or you risk messing it up:
public function getStatuses($dates)
{
$query = DB::table('tickets');
if ($dates['from'])
$query->where('from', $dates['from']);
if ($dates['to'])
$query->where('to', $dates['to']);
$query->select('Active');
return $query->get()->toArray();
}
In Laravel 4, its necessary to assign the get method to a variable
public function scopeGetPosts($query, $this_user = NULL){
$results = DB::table('post')
->select('*')
->where('post_status','=','publish');
if( $this_user != NULL ){
$results->where('post_author','=',$this_user->user_id);
}
$data = $results->orderBy('created_at', 'desc')
->get();
if( empty( $results ) )
$data = 'no results';
return $data;
}
In Laravel Eloquent :
$query = ModelName::where('status',1);
if($userId){
$query->where('user_id',$userId);
}
if($limit){
$query->limit($limit);
}
$result = $query->get();
I am having trouble getting two tables and passing them to controller:
IN A MODEL:
function get_all_entries() {
$query = $this->db->get('entry');
return $query->result();
$this->db->select('entry_id , count(comment_id) as total_comment');
$this->db->group_by('entry_id');
$comment = $this->db->get('comment');
return $comment->result();
}
IN A CONTROLLER:
$data['query'] = $this->blog_model->get_all_entries();
$this->load->view('blog/index',$data);
How do I return $query and $comment variables to controller? I think I am doing it wrong.
Use this because you are not allowed to return twice in the same method
function get_all_entries()
{
$query = $this->db->get('entry');
$data[] = $query->result();
$this->db->select('entry_id , count(comment_id) as total_comment');
$this->db->group_by('entry_id');
$comment = $this->db->get('comment');
$data[] = $comment->result();
return $data;
}
EDITS:
In controller
function index(){
$this->load->model('mymodel');
$result = $this->mymodel->get_all_entries();
$entries = $result[0] ;
$comments = $result[1] ;
$data['entries'] = $entries;
$data['comments '] = $comments;
}
Your issue is that you're returning $query->result() in first place, return function halts the current function, so the next steps are not being processed.
Best way would be to create two methods for either $query get and $comment get.
An alternative to your issue would be
function get_all_entries() {
$query = $this->db->get('entry');
$this->db->select('entry_id , count(comment_id) as total_comment');
$this->db->group_by('entry_id');
$comment = $this->db->get('comment');
return array($query->result(),$comment->result());
}
Then in your controller
list($data['query'],$data['comment']) = $this->blog_model->get_all_entries();
$this->load->view('blog/index',$data);
I'm hoping to use Google Maps on my site.
My addresses are stored in a DB. I’m pulling up a page where the information is all dynamic. For example: mysite.com/site/business/5 (where 5 is the id of the business).
Let’s say I do a query like this:
function addressForMap($id) {
$this->db->select('b.id, b.busaddress, b.buscity, b.buszip');
$this->db->from('business as b');
$this->db->where('b.id', $id);
$this->db->limit(1);
// add a limit
$this->db->limit(1);
// get the results.. cha-ching
$q = $this->db->get();
// any results?
if($q->num_rows() !== 1)
{
return FALSE;
}
return $q->row();
}
How can I output the info to the Google Maps API correctly so that it displays the map appropriately?
The API interface takes the results like this: $marker['address'] = 'Crescent Park, Palo Alto';.
Here's what I have in the controller:
$marker = array();
$address = $this->Business_model->addressForMap($id); //Get result row
$marker['address'] = $address->busaddress .' '.$address->buscity .', '. $address->buszip;
The MODEL
function addressForMap($id)
{
$this->db->select('b.id, b.busaddress, b.buscity, b.buszip');
$this->db->from('business as b');
$this->db->where('b.id', $id);
// add a limit
$this->db->limit(1);
// get the results.. cha-ching
$q = $this->db->get();
// any results?
if($q->num_rows() !== 1)
{
return FALSE;
}
return $q->row();
}
The CONTROLLER
function your_controller_method($id)
{
$data = $this->Business_model->addressForMap($id);
// did we get any results?
if($data === FALSE)
{
show_error();
return;
}
$marker['address'] = $data->busaddress.' '.$data->buscity.', '.$data->buszip;
}
Make sure you validate that $id is an actual numerical id. It's a good thing to do before actually performing the query.. IMO.
EDIT #2: See changed code above
EDIT #1: From your comment and changes
You've got this:
return $this->db->get();
when, based on the rest of your code, it should be this:
$query = $this->db->get();
When you return the query object, the variable $address gets assigned the CI result object. so, in your controller, you would actually have to do something like this:
$address = $this->Business_model->addressForMap($id);
$row = $address->row();
$marker['address'] = $row->busaddress .' '.$row->buscity .', '. $row->buszip;
Still... I would suggest changing return to $query = and you could keep your controller as it is.
Here's the Final correct code:
For the Controller:
$address = $this->Business_model->addressForMap($id); //Get result row
$config['apikey'] = 'google-api-key';
$config['center_address'] = $address->busaddress .', '. $address->buscity;
$this->googlemaps->initialize($config);
$marker = array();
// $marker['address'] = $address->busaddress .' '.$address->buscity .', '. $address->buszip;
$marker['address'] = $address->busaddress .', '. $address->buscity;
$this->googlemaps->add_marker($marker);
$data['map'] = $this->googlemaps->create_map();
$data['address'] = $address->busaddress .', '.$address->buscity;
For the Model:
function addressForMap($id) {
$this->db->select('b.id, b.busaddress, b.buscity, b.buszip');
$this->db->from('business as b');
$this->db->where('b.id', $id);
$this->db->limit(1);
// add a limit
$this->db->limit(1);
// get the results.. cha-ching
$q = $this->db->get();
// any results?
if($q->num_rows() !== 1)
{
return FALSE;
}
return $q->row();
}
Thanks for using my library. It looks I posted the solution on my blog at near enough exactly the same time as you did on here :-P
Glad to hear you got it sorted though!