Json returns a duplicate value using codeigniter - php

I am trying to fetch a data for each chkey with a related value as a group in codeigniter. When there are a 2 or more chkey then code is work properly.
But when there is a only 1 chkey then it shows value of that chkey but it is shows extra chkey:null,value:null in json.
Related json for chkey is 1 is as follows'
[{"unit_id":"8","CHGRAPHUpdatetime":{"time":"2018-03-15 00:00:00,2018-03-15 00:00:00,2018-03-15 00:00:00,2018-03-15 00:00:00"},"channelGraph":[{"chkey":"ch1","list":"2,-30,12,20"},{"chkey":"null","list":"null"}]}]
Expected is,
[{"unit_id":"8","CHGRAPHUpdatetime":{"time":"2018-03-15 00:00:00,2018-03-15 00:00:00,2018-03-15 00:00:00,2018-03-15 00:00:00"},"channelGraph":[{"chkey":"ch1","list":"2,-30,12,20"}]}]
Could you please help me to resolve this issue.
model code-
public function chGraph($unitid){
$this->db->select("unit_id");
$this->db->from("device_unit");
$this->db->where('unit_id', $unitid);
$query = $this->db->get();
$unit = $query->result_array();
$j = 0;
foreach($unit as $row) {
$unit[$j]['CHGRAPHUpdatetime'] = $this->UnitCHGRAPHUpdatetime($row['unit_id']);
$unit[$j++]['channelGraph'] = $this->UnitCHGRAPHDetails1($row['unit_id']);
}
return $unit;
}
public function UnitCHGRAPHDetails1($unit_id)
{
$this->db->select('distinct(chkey)','chvalue');
$this->db->from('channel_info');
$query = $this->db->get();
$channelgraphData = $query->result_array();
$m = 0;
foreach($channelgraphData as $row) {
$chvalueQuery = 'SELECT chkey, GROUP_CONCAT(chvalue)as list FROM channel_info where chkey= "'. $row['chkey'] .'" and unit_id='. $unit_id .'';
$response = $this->db->query($chvalueQuery)->row();
$channelgraphData[$m++] = $response;
}
return $channelgraphData;
}
controller code-
public function chGraph()
{
$unitid = $this->uri->segment('3');
$GraphDetails = $this->device_model->chGraph($unitid);
echo json_encode($GraphDetails);
}

You could add a GROUP BY at the end of the statement to eliminate the null results :
$chvalueQuery = 'SELECT chkey, GROUP_CONCAT(chvalue)as list FROM channel_info where chkey= "'. $row['chkey'] .'" and unit_id='. $unit_id .' GROUP BY chkey';

Related

php - Codeigniter Increment

So I have this function that gets the total number of rows in a table.
This is my Code:
public function get_reservation()
{
$this->db->select('COUNT(*) as res_no ');
$this->db->from('reservation_details');
$query = $this->db->get()->result();
echo json_encode($query);
}
And it returns this JSON data
[{"res_no":"2"}]
What I want is to increment its value to 1 and return like this
[{"res_no":"3"}]
So far I have tried something like this
This is the my Code:
public function get_reservation()
{
$query = $this->db->select('COUNT(*) as res_no ')->from('reservation_details')->get();
$price = $query->row()->res_no;
$price = $price + 1;
echo json_encode($price);
}
But it only return 3
Hope this will help you :
Use CI query helper count_all to count all record of a table
public function get_reservation()
{
$count = $this->db->count_all('reservation_details');
$price = $count + 1;
$data['res_no'] = $price;
echo json_encode($data);
}
For more : https://www.codeigniter.com/userguide3/database/helpers.html#information-about-your-database

how to get sum of database column in codeigniter?

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();
}

This query show me with this active record

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);

select max codeigniter

Im trying to get an max value with codeigniter from an table but it isnt working. This is the error i get:
Severity: 4096
Message: Object of class CI_DB_mysql_result could not be converted to
string
Filename: database/DB_active_rec.php
Line Number: 427
This is my function:
public function getPeriodeNummer($bedrijf_id) {
$this->db->select_max('id');
$this->db->where('bedrijf_id', $bedrijf_id);
$result = $this->db->get('rapporten');
$this->db->select('periode_nummer');
$this->db->where('rapporten_id', $result);
$query = $this->db->get('statistieken_onderhoud');
$data = $query + 1;
return $data;
}
What im trying to do is as followed:
Select the highest id where bedrijf_id = $bedrijf_id from rapporten.
Select the periode_nummer from statistieken_onderhoud where rapporten_id = the highest id i got from step 1.
Add 1 to the periode_nummer i got from step 2 and return that number.
Thanks in forward for your help!
Try
public function getPeriodeNummer($bedrijf_id) {
$this->db->select_max('id');
$this->db->where('bedrijf_id', $bedrijf_id);
$res1 = $this->db->get('rapporten');
if ($res1->num_rows() > 0)
{
$res2 = $res1->result_array();
$result = $res2[0]['id'];
$this->db->select('periode_nummer');
$this->db->where('rapporten_id', $result);
$query = $this->db->get('statistieken_onderhoud');
if ($query->num_rows() > 0)
{
$row = $query->result_array();
$data['query'] = 1 + $row[0]['periode_nummer'];
}
return $data['query'];
}
return NULL;
}
Try this:
$this->db->select_max('display_sequence');
$this->db->from('acl_menu');
$query = $this->db->get();
$r=$query->result();
Display Sequence is your column name & acl_menu is your table name.
You can't use an object as a string. Use this:
public function getPeriodeNummer($bedrijf_id) {
$this->db->select_max('id');
$this->db->where('bedrijf_id', $bedrijf_id);
$result = $this->db->get('rapporten');
$this->db->select('periode_nummer');
$this->db->where('rapporten_id', $result);
$query = $this->db->get('statistieken_onderhoud');
// fetch first row in object
$result = $query->row();
$data = $result + 1;
return $data;
}
$this->db->select_max('id', 'max_id');
$query = $this->db->get('video_processing');
return $query->row();
try the above:
I think the $query variable is holding a mysql result resource and it cannot be used as a String or in this case an Integer.
You could try this way:
$data = mysql_result($query,0) + 1;
Shortest:
$this->db->select_max('id', 'max_id')->get('video_processing')->row();

Passing Results from SQL to Google Maps API in CodeIgniter

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!

Categories