How to get Select max value in codeigniter - codeigniter

Controller:
$next_id = $this->o->next_id();
$data['next_id']=$next_id;
Model:
public function next_id(){
$this->db->select_max('p_ori_id');
$max = $this->db->get('orientation_master');
if($max==0){
$next_id = 1;
}else{
$next_id = 1+$max;
}
return $next_id;
}
Return Error:
Object of class CI_DB_mysqli_result could not be converted to int
Please solve problem..

No offense to #pradeep but you may have some unexpected results if you don't have any rows. I suggest:
public function next_id()
{
$this->db->select_max('p_ori_id', 'max');
$query = $this->db->get('orientation_master');
if ($query->num_rows() == 0) {
return 1;
}
$max = $query->row()->max;
return $max == 0 ? 1 : $max + 1;
}

Hope this will help you:
public function next_id()
{
$this->db->select_max('p_ori_id', 'max');
$query = $this->db->get('orientation_master');
// Produces: SELECT MAX(p_ori_id) as max FROM orientation_master
$max = $query->row()->max;
if($max == 0){
$next_id = 1;
}else{
$next_id = $max+1;
}
return $next_id;
}
For more : https://www.codeigniter.com/user_guide/database/query_builder.html

You are getting that error becuase $max is a result set object and not an integer record value like you're trying to use it.
You can try this function to get the next id.
Modified function:
public function next_id(){
$this->db->select_max('p_ori_id', 'max');
$result = $this->db->get('orientation_master');
$row = $result->row_array();
$next_id = isset($row['max']) ? ($row['max']+1) : 1;
return $next_id;
}
If the column is auto increment, you can use the below code instead.
Alternative:
public function next_id() {
$sql_string = "SELECT `auto_increment` FROM INFORMATION_SCHEMA.TABLES WHERE table_name = '".$this->db->dbprefix."orientation_master'";
$query = $this->db->query($sql_string);
$row = $query->row_array();
return $row['auto_increment'];
}

Related

model and controller query to merge timein and timeout with single row in codeigniter

Please teach me how can I achieve this(Codeigniter framework)
Please see images that I want to achieve thank you.
and I'm also new to codeigniter and want to understand the answer.
enter image description here
Here is my database:
enter image description here
model
public function get_attendance_employees() {
$sql = 'SELECT * FROM tbl_employee';
//$binds = array(1);
$query = $this->db->query($sql);
return $query;
}
public function attendance_first_in_check($userid,$attendance_date) {
$sql = "SELECT * FROM tbl_employee_time_log as time_log WHERE userid = ? and substring(time_log.time,1,10) = ? and type = 'timein' limit 1";
$binds = array($userid,$attendance_date);
$query = $this->db->query($sql,$binds);
return $query;
}
public function attendance_first_in($userid,$attendance_date) {
$sql = "SELECT * FROM tbl_employee_time_log as time_log WHERE userid = ? and substring(time_log.time,1,10) = ? and type = 'timein'";
$binds = array($userid,$attendance_date);
$query = $this->db->query($sql, $binds);
return $query->result();
}
public function attendance_first_out_check($userid,$attendance_date) {
$sql = "SELECT * FROM tbl_employee_time_log as time_log WHERE userid = ? and substring(time_log.time,1,10) = ? and type = 'timeout' order by id desc limit 1";
$binds = array($userid,$attendance_date);
$query = $this->db->query($sql, $binds);
return $query;
}
public function attendance_first_out($userid,$attendance_date) {
$sql = "SELECT * FROM tbl_employee_time_log as time_log WHERE userid = ? and substring(time_log.time,1,10) = ? and type = 'timeout' order by id desc limit 1";
$binds = array($userid,$attendance_date);
$query = $this->db->query($sql, $binds);
return $query->result();
}
controller
public function attendance_bio()
{
$session = $this->session->userdata('username');
if(!empty($session)){
$this->load->view("admin/timesheet/attendance_bio", $data);
} else {
redirect('admin/');
}
// Datatables Variables
$draw = intval($this->input->get("draw"));
$start = intval($this->input->get("start"));
$length = intval($this->input->get("length"));
$attendance_date2 = $this->input->get("attendance_date"); //string
//$ref_location_id = $this->input->get("location_id");
//$convert_atten = strtotime($attendance_date2); //int value
//$attendance_date = $convert_atten->format('m-d-Y');
$attendance_date = date("m-d-Y",strtotime($attendance_date2));
//$timein = $this->Bio_model->get_attendance_date();
//$timein = $this->Bio_model->get_attendance_timein($get_day);
//$timein = $this->Bio_model->get_all();
$employee = $this->Bio_model->get_attendance_employees();
$data = array();
//var_dump($attendance_date);
foreach($employee->result() as $r){
$check = $this->Bio_model->attendance_first_in_check($r->userid,$attendance_date);
if($check->num_rows() > 0){
// check clock in time
$first_in = $this->Bio_model->attendance_first_in($r->userid,$attendance_date);
//$first_in2 = $first_in[0]->time->format('m-d-Y');
// clock in
$clock_in = new DateTime(strtotime($first_in[0]->time));
//$clock_in2 = $clock_in->format('H:i');
$clock_in2 = date_format($clock_in->time, 'H:i');
//$clock_in2 = var_dump($clock_in);
} else {
$clock_in2 = '-';
$clock_in = '-';
}
$check_out = $this->Bio_model->attendance_first_out_check($r->userid,$attendance_date);
if($check_out->num_rows() == 1){
$first_out = $this->Bio_model->attendance_first_out($r->userid,$attendance_date);
//$first_out2 = $firs
$clock_out = new DateTime(strtotime($first_out[0]->time));
if ($first_out[0]->time!='') {
//$clock_out2 = $clock_out->format('H:i');
//$clock_out2 = date('H:i',$clock_out);
$clock_out2 = date_format($clock_out->time, 'H:i');
} else {
$clock_out2 = '-';
}
}else {
$clock_out2 = '-';
$clock_out = '-';
}
$data[] = array(
$r->userid,
$attendance_date,
$clock_in2,
$clock_out2,
);
}
$output = array(
"draw" => $draw,
"recordsTotal" => $employee->num_rows(),
"recordsFiltered" => $employee->num_rows(),
"data" => $data
);
echo json_encode($output);
exit();
}
Thank you for providing more information on the topic and the code you have attempted so far. I have supplied an algorithm which I believe will work for you.
Contoller:
<?php namespace App\Controllers;
use App\Models\EmployeeTimeLog;
class Home extends BaseController
{
public function index($employeeId)
{
// get all between dates
$emplyeeModel = new EmployeeTimeLog();
// get one week before today - for example
$startDate = date("Y-m-d", strtotime("-1 week"));
$endDate = date("Y-m-d");
// get clock-in and clock-out for employee between dates
$timeIn = $emplyeeModel->getTimeIn($employeeId, $startDate, $endDate)->getResult();
$timeOut = $emplyeeModel->getTimeOut($employeeId, $startDate, $endDate)->getResult();
$timeInIndex = 0;
$timeOutIndex = 0;
$output = [];
$nextDate = $startDate;
// loop through all the days between start and end date
while($nextDate < $endDate){
// get the lowest "timein" datetime which is the same date as the search date $nextDate
$nextTimeIn = NULL;
while($timeInIndex < count($timeIn) && date("Y-m-d", strtotime($timeIn[$timeInIndex]->Time)) == $nextDate){
if(is_null($nextTimeIn)){
$nextTimeIn = $timeIn[$timeInIndex];
}
$timeInIndex ++;
}
// get the highest "timeout" datetime which is the same day as the search date $nextDate
$nextTimeOut = NULL;
while($timeOutIndex < count($timeOut) && date("Y-m-d", strtotime($timeOut[$timeOutIndex]->Time)) == $nextDate){
$nextTimeOut = $timeOut[$timeOutIndex];
$timeOutIndex ++;
}
// enter into a 2 dimentional array with
// index 0 = timein
// index 1 = timeout
$output[] = [$nextTimeIn, $nextTimeOut];
// get the next date
$nextDate = date('Y-m-d', strtotime($nextDate. ' + 1 days'));
}
// return view with data
return view('welcome_message', ["output" => $output]);
}
}
Model:
<?php
namespace App\Models;
use CodeIgniter\Model;
class EmployeeTimeLog extends Model{
private $tableName = "tbl_employee_time_log";
public function __construct(){
$db = \Config\Database::connect();
$this->builder = $db->table($this->tableName);
}
private function timeData($employeeId, $startDate, $endDate){
// builder function DRY
$this->builder->where("EmployeeId", $employeeId);
$this->builder->where("Time >", $startDate);
$this->builder->where("Time <", $endDate);
$this->builder->orderBy("Time", "ASC");
}
public function getTimeIn($employeeId, $startDate, $endDate){
// call builder function and add timeIn to only get clock in times
$this->timeData($employeeId, $startDate, $endDate);
$this->builder->where("Type", "timein");
return $this->builder->get();
}
public function getTimeOut($employeeId, $startDate, $endDate){
// call builder function and add timeout to only get clock out times
$this->timeData($employeeId, $startDate, $endDate);
$this->builder->where("Type", "timeout");
return $this->builder->get();
}
}
?>
View:
<!DOCTYPE html>
<html lang="en">
<head>
<title>Timesheets</title>
</head>
<body>
<h1>Timesheets</h1>
<?php
echo "<h1>Times</h1>";
foreach ($output as $times) {
echo "Time in: ";
if(!is_null($times[0])){
echo $times[0]->Time;
}else{
echo "-";
}
echo " Time out: ";
if(!is_null($times[1])){
echo $times[1]->Time;
}else{
echo "-";
}
echo "<br>";
}
?>
</body>
</html>
Output:
Database:
The whole algorithm works by searching through the date between the start and end date of the dates provided. You can then check any timein and timeout values which have the same date as the loop date. If a date cannot be found, the default is NULL which is replaced by "-" in the view.
The algorithm specifically gets the earliest timein and the latest timeout value for the employee. This means that if the employee clocks-in twice in one day the earliest date will be used and the opposite for clock-out.
This algorithm specifically works for one employee, but just use your select * employees and loop through instead of the employeeId on the controller. You may want to look in the documentation for the Query Builder in CodeIgniter it makes querying the database much easier, and will escape data to protect from SQL Injections etc.
It could be better to redesign your database table and check on insert rather than manipulate on select. Where you have one row for each day and the timein and timeout which represent the time. Something like this:
You can check to see if the date already exists, if so override the current value if needed. If the current date doesn't exist for that employee create a new record.
If you need any clarification, let me know,
Thanks,

How to add another array value in codeigniter using getRecords

The orignial code was like this , I want to get landline_no value also in getRecords, How to do that
public function checklead() {
$lead = $_POST['number'];
$check = $this->common_model->getRecords('leads',array("phone_no"=>$lead));
if(count($check) > 0) {
$lead = $this->common_model->getRecored_row('leads',array("phone_no"=>$lead));
if($lead->assignto_self != 0) {
$assignto = $lead->assignto_self;
$key = 'Self Assign';
} else if($lead->assignto_se != 0) {
$assignto = $lead->assignto_se;
$key = '';}
What I have achieved so far,but not getting array values from getRecords
$lead = $_POST['number'];
$check = $this->common_model->getRecords('leads',array("phone_no"=>$lead),array("landline_no"=>$lead));
//echo "<pre>";
//print_r($check);
//echo $check[0]['landline_no'];exit;
if(count($check) > 0) {
$lead = $this->common_model->getRecored_row('leads',array("phone_no"=>$lead,"landline_no"=>$check[0]['landline_no']));
Code for getRecords:
function getRecords($table,$db = array(),$select = "*",$ordercol = '',$group = '',$start='',$limit=''){
$this->db->select($select);
if(!empty($ordercol)){
$this->db->order_by($ordercol);
}
if($limit != '' && $start !=''){
$this->db->limit($limit,$start);
}
if($group != ''){
$this->db->group_by($group);
}
$q=$this->db->get_where($table, $db);
return $q->result_array();
}
// Get Recored row
public function getRecored_row($table,$where)
{
$q = $this->db->where($where)
->select('*')
->get($table);
return $q->row();
}
Check my answer: This code also working well, i have written, but i am not sure , this logic is correct or not kindly check this one.
public function checklead() {
$lead = $_POST['number'];
if($this->common_model->getRecords('leads',array("phone_no"=>$lead)))
{
$check=$this->common_model->getRecords('leads',array("phone_no"=>$lead));
}
else
{
$check=$this->common_model->getRecords('leads',array("landline_no"=>$lead));
}
echo "<pre>";
//echo $check;
//print_r($check); exit;
$p= $check[0]['phone_no'];
$l= $check[0]['landline_no'];
// exit;
if(count($p) > 0 || count($l)>0) {
$lead = $this->common_model->getRecored_row('leads',array("phone_no"=>$p));
$lead1 = $this->common_model->getRecored_row('leads',array("landline_no"=>$l));
if($lead->assignto_self != 0 || $lead1->assignto_self != 0) {
$assignto = $lead->assignto_self;
$key = 'Self Assign';
} else if($lead->assignto_se != 0 || $lead1->assignto_se != 0) {
$assignto = $lead->assignto_se;
$key = '';
}else if($lead->assignto_tl != 0 || $lead1->assignto_tl != 0) {
$assignto = $lead->assignto_tl;
$key = '';
} else if($lead->uploaded_by != 0 || $lead1->uploaded_by != 0) {
$assignto = $lead->uploaded_by;
$key = 'Uploaded by';
}
$user = $this->common_model->getRecored_row('admin',array("id"=>$assignto));
$role = $this->common_model->getRecored_row('role',array("id"=>$user->role));
$this->session->set_flashdata('message', array('message' => 'This Lead Already exist with '.$user->name.' ('.$role->role.') '.' ','class' => 'danger'));
redirect(base_url().'leads');
} else {
redirect(base_url().'leads/add_newlead/'.$lead);
}
}
There does not seem to be any reason to use getRecords(). The $check value has no useful purpose and creating it is a waste of resources.
We don't need $check because getRecord_row() will return the "lead" if found so the only check needed is to see if getRecord_row() returns anything. getRecord_row() uses the database function row() which returns only one row or null if no rows are found. Read about row() here.
If what you want is to find the "lead" that has either a "phone_no" or a "landline_no" equal to $_POST['number'] then you need to use a custom string for the where clause. (See #4 at on this documentation page.) You need a custom string because getRecord_row() does not allow any other way to ask for rows where a='foo' OR b='foo'. Here is what I think you are looking for.
public function checklead()
{
// use input->post() it is the safe way to get data from $_POST
$phone = $this->input->post('number');
// $phone could be null if $_POST['number'] is not set
if($phone)
{
$lead = $this->common_model->getRecored_row('leads', "phone_no = $phone OR landline_no = $phone");
// $lead could be null if nothing matches where condition
if($lead)
{
if($lead->assignto_self != 0)
{
$assignto = $lead->assignto_self;
$key = 'Self Assign';
}
else if($lead->assignto_se != 0)
{
$assignto = $lead->assignto_se;
$key = '';
}
}
}
}
The main difference between getRecords() and getRecord_row() is the number of records (rows of data) to return. getRecord_row() will return a maximum of one record while getRecords() might return many records.
getRecords() accepts arguments that allow control of what data is selected ($db, $select), how it is arranged ($ordercol, $group), and the number of rows to retrieve ($limit) starting at row number x ($start) .

doctrine query with parameters having multiple values

I want to make a doctrine query in which each parameters can have multiple values (coming from a select multiple).
I have a table with a 'type' parameter that can have value of 1, 2, 3 or 4 and an 'online' parameter that can be 0 or 1.
My query so far is the following :
$query = $this->createQueryBuilder('properties');
if (array_key_exists('type', $searchValues)) {
$types = $searchValues['type'];
$iterator = 0;
foreach ($types as $type) {
if ($iterator == 0) {
$query->andWhere('properties.idPropertyType = ' . $type);
} else {
$query->orWhere('properties.onlineProperties = ' . $type);
}
$iterator++;
}
}
if (array_key_exists('status', $searchValues)) {
$status = $searchValues['status'];
$iterator = 0;
foreach ($status as $statu) {
if ($iterator == 0) {
$query->andwhere('properties.onlineProperties = ' . $statu);
} else {
$query->andWhere('properties.onlineProperties = ' . $statu);
}
$iterator++;
}
}
$properties = $query->getQuery()->getResult();
In the case of a search with parameter type = 1 and online = 0 and 1, I have results where type is another value than 1. I understand the reason why but I cannot figure out a proper way to make my query.
You don't need to build your query by hand manually, just use the (in) function from the QueryBuilder class. Try this:
$query = $this->createQueryBuilder('properties');
if(array_key_exists('type', $searchValues)){
$types = $searchValues['type'];
$query->andWhere($query->expr()->in('properties.idPropertyType', $types));
}
if(array_key_exists('status', $searchValues)){
$status = $searchValues['status'];
$query->andwhere($query->expr()->in('properties.onlineProperties', $status));
}
$properties = $query->getQuery()->getResult();

how to count all the array of data in controler

I want to count the array of data got by using postgresql using codeigniter.I used foreach loop and used count($row['zero']) to count but it results only 1.please guide me.
Here is my controller
public function indicators($pcode = '', $dcode = '') {
$this->data['p_code'] = $pcode;
$this->data['d_code'] = $dcode;
$this->data['pcode'] = $this->employment_model->get_project();
$this->data['attend_household'] = $this->employment_model->household_absent_all($dcode);
var_dump($this->data['attend_household']);
die();
foreach($this->data['attend_household'] as $row){
if($row['zero']>0){
$this->data['zerroo']=count($row['zero']);
}
}
if (count($this->data['attend_household']) > 0) {
$this->data['attend_household'] = $this->data['attend_household'][0];
}
// var_dump($this->data);
$this->load->view("employment_info", $this->data);
}
Here is my model
function household_absent_all($dcode) {
$dcode_query = "";
if ($dcode != '') {
if ($dcode == 'all') {
$dcode_query = "";
} else {
$dcode_query = "where t.dcode='$dcode'";
}
}
$sql = "select (100-(sum(days_worked)/sum(days_offered))*100) as zero,regno,sum(days_offered) as days_offered,sum(days_worked) as days_worked
from(
select*
from assets.tblprojects a
join(
select pcode as project,hh_jobcard_no
from employment.work_group_member
)wg on a.pcode=wg.project
join(
select regno,at.days_offered,at.days_worked
from employment.registration_hh_member
join(
select pcode as a_pcode,hh_jobcard_no as jobcard,mem_id,
sum((shift_1*0.5)+(shift_2*0.5)) as days_worked,count(adate) as days_offered
from employment.attendence
group by a_pcode,jobcard,mem_id
)at on regno=at.jobcard and s_no=at.mem_id
)rhm on wg.hh_jobcard_no=rhm.regno
)t
group by regno
$dcode_query
";
$result = $this->db->query($sql)->result_array();
return $result;
}
try like this
$i=0;
foreach($this->data['attend_household'] as $row){
if($row['zero']>0){
$i++;
}
}
$this->data['zerroo']=$i;
how about using the num_rows() as your counter.
if($num = $result->num_rows() >=1){
$result = array('result_set'=>$result->result_array(),'result_count'=>$num);
}else{
$result = array('result_set'=>FALSE,'result_count'=>FALSE);
}
return $result;
then on your controller you can use it as $variable['result_count'] for count and $variable['result_set'] for the data results.

CI pagination double query

I am working in CI Framework. For pagination i use two queries, one for required output using limit, and another to count total number of rows. Is there any other way like both can be done from single query?
My query is:
{
$searchtxt = $this->input->post('searchtxt');
$datefrom = $this->input->post('fromdate');
$todate = $this->input->post('todate');
$status= $this->input->post('order_status');
$sc_id = $this->input->post('sc_id');
if($sc_id){
$this->db->where('('.'o.requested_sc_id = '.$sc_id.' OR o.requesting_sc_id = '.$sc_id.')');
//$this->db->where('o.requesting_sc_id =',$sc_id);
}
if ($status){
$this->db->where('o.order_status =',$status);
}
if ($status != '' && $status == 0 ){
$this->db->where('o.order_status = 0');
}
if($searchtxt){
$this->db->like('o.order_number',$searchtxt);
}
if($datefrom)
{
$this->db->where('o.order_dt >=', date("Y-m-d",date_to_timestamp($datefrom)));
}
if($todate)
{
$this->db->where('o.order_dt <=', date("Y-m-d",date_to_timestamp($todate)));
}
if ($this->session->userdata('usergroup_id')!=1 && $this->session->userdata('usergroup_id')!= 2 && $this->session->userdata('usergroup_id')!=6 ){
$this->db->where('('.'o.requested_sc_id = '.$this->session->userdata('sc_id').' OR o.requesting_sc_id = '.$this->session->userdata('sc_id').')');
//$this->db->where('o.requesting_sc_id = '.$this->session->userdata('sc_id'));
}
$this->db->select('o.order_id,o.order_number,o.order_dt,o.call_id,c.call_uid,o.order_status,o.order_dt,sc.sc_name,e.engineer_name');
$this->db->from($this->table_name.' AS o');
$this->db->join($this->mdl_callcenter->table_name.' AS c','c.call_id=o.call_id','left');
$this->db->join($this->mdl_servicecenters->table_name.' AS sc' ,'sc.sc_id=o.requested_sc_id','left');
$this->db->join($this->mdl_engineers->table_name.' AS e', 'e.engineer_id = o.engineer_id','left');
$this->db->order_by('o.order_status ASC,o.order_dt DESC,o.order_created_ts DESC');
if(isset($page['limit'])){
$this->db->limit((int)$page['limit'],(int)$page['start']);
}
$result = $this->db->get();
//echo $this->db->last_query();
if ($status){
$this->db->where('o.order_status =',$status);
}
if ($status != '' && $status == 0 ){
$this->db->where('o.order_status = 0');
}
if($sc_id){
$this->db->where('o.requesting_sc_id =',$sc_id);
}
if($searchtxt){
$this->db->like('o.order_number',$searchtxt);
}
if($datefrom)
{
$this->db->where('o.order_dt >=', date("Y-m-d",date_to_timestamp($datefrom)));
}
if($todate)
{
$this->db->where('o.order_dt <=', date("Y-m-d",date_to_timestamp($todate)));
}
//if ($this->session->userdata('global_admin')!=1){
if ($this->session->userdata('usergroup_id')!=1 && $this->session->userdata('usergroup_id')!= 2 && $this->session->userdata('usergroup_id')!=6 ){
$this->db->where('o.requested_sc_id = '.$this->session->userdata('sc_id').' or o.requesting_sc_id = '.$this->session->userdata('sc_id'));
}
$this->db->select('o.order_id');
$this->db->from($this->table_name.' AS o');
$this->db->join($this->mdl_callcenter->table_name.' AS c','c.call_id=o.call_id','left');
$this->db->join($this->mdl_servicecenters->table_name.' AS sc' ,'sc.sc_id=o.requested_sc_id','left');
$this->db->join($this->mdl_engineers->table_name.' AS e', 'e.engineer_id = o.engineer_id','left');
$result_total = $this->db->get();
$orders['list'] = $result->result();
$orders['total'] = $result_total->num_rows();
return $orders;
}
Here is some explanation for this.
function($limit,$offset){
$this->db
->select("SQL_CALC_FOUND_ROWS emp", FALSE)
->select("*")
->from('tbl1')
->limit($limit, $offset);
$data["query_result"] = $this->db->get()->result_array();
$query = $this->db->query('SELECT FOUND_ROWS() AS `Count`');
$data["total_rows"] = $query->row()->Count;
return $data;
}
Here you see you are forced to get total count using another query.
Of course this is not what you want but it is impossible with single query using mysql.
But here is a php way.
function($limit,$offset){
$this->db
->select("*")
->from('tbl1');
$data["query_result"] = $this->db->get()->result_array();
$data["total_rows"] = array_slice($data["query_result"], $offset, $limit);
return $data;
}
This can be achieved with single query but involves php to get the desired result.

Resources