display record with specific date in codeigniter - php

I want to select record with certain date and id. My datetime format in database is 2018-02-23 08:38:45. I've try this in my model but it always return the records with specific id only. My date format in $tgl is 23-01-2018 so I change the format using $date = date('Y-m-d', strtotime($tgl) );
public function spesific_odontogram($id_pasien, $date){
$query = "SELECT * FROM odontogram WHERE DATE('inserted_at') = $date AND id_pasien=$id_pasien";
$record = $this->db->query($query);
if ($record->row_array()>0) {
return $record->result_array();
}
return false;
//return $record;
}
Here's my controller
public function spesific_odontogram(){
$id_pasien=$_POST['id_pasien'];
$tgl=$_POST['tgl'];
$date = date('Y-m-d', strtotime($tgl) );
$data['record']=$this->m_pasien->spesific_odontogram($id_pasien, $date);
if ($this->input->is_ajax_request())
{
echo json_encode($data);
exit;
}
}

Use Date variable like '$date' instead of $date. Also make sure date format are same
public function spesific_odontogram($id_pasien, $date){
$query = $this->db->query("SELECT * FROM odontogram WHERE inserted_at = '$date' AND id_pasien=$id_pasien");
if ($query->row_array()>0) {
return $query->result_array();
}
return false;
}

Try using below query on your model :
public function spesific_odontogram($id_pasien, $date){
$query = "SELECT * FROM odontogram WHERE inserted_at >= $date AND inserted_at < $date + INTERVAL 1 DAY AND id_pasien=$id_pasien";
$record = $this->db->query($query);
if ($record->row_array()>0) {
return $record->result_array();
}
return false;
//return $record;
}
It basically check for only matches date record without calculate DATE() value of every row

Related

Get current date records from table with different time zone

This question is related to my previews one: How to change time zome in different tables in Laravel
After I mark the answer, discover a problem:
When user load the page it need to gives him records for the current day.
For example from 00:00:00 to now.
The problem is that the controller is asking the DB to give records from 00:00:00 in UTC, after this my model(in the link above) parsing it to LOCAL time.
This local time is Europe/Sofia (+3 hours), causing to miss 3 records from today starting with 03:00:00.
Any idea how to fix it?
The controller:
function getdata_chart(Request $request)
{
$start_date = date('d-m-Y 00:00:00');
$end_date = date('d-m-Y 23:59:59');
if($request->start_date != '' && $request->end_date != '')
{
// if user fill dates
$dateScope = array($request->start_date ." 00:00:00", $request->end_date ." 23:59:59");
} else {
// default load page - today
$dateScope = array($start_date, $end_date);
};
$students = MeasCanal::whereBetween('recordtime', $dateScope)
->selectRaw('recordtime')
->selectRaw('max(formattedvalue) filter (where fullname = \'Данни.Кота\') as iazovir')
->selectRaw('max(formattedvalue) filter (where fullname = \'Данни.Температура\') as temperatura350')
->where(function ($query) {
$query->where('fullname', 'like', "Язовир.Данни.Кота")
->orWhere('fullname', 'like', "ГСК_11_350.Данни.Температура");
})
->groupBy('recordtime')
->orderBy('recordtime')
->get();
return response()->json($students);
}
return response()->json($students);
}
The model:
class MeasCanal extends Model
{
protected $connection = 'MeasCanal';
protected $table = 'meas_kanal';
protected $fillable = ['fullname','formattedvalue','recordtime','qualitydesc','statedesc','id'];
/**
* Get the user's recordtime.
*
* #param string $value
* #return string
*/
public function getRecordtimeAttribute($value)
{
return Carbon::parse($value)->timezone('Europe/Sofia')->toDateTimeString();
}
}
You have to map the user input date from the DB timezone to the user timezone by calling the carbon method and array map function. and call the query as it is.
function getdata_chart(Request $request) {
$start_date = date('d-m-Y 00:00:00');
$end_date = date('d-m-Y 23:59:59');
if($request->start_date != '' && $request->end_date != '')
{
// if user fill dates
$dateScope = array($request->start_date ." 00:00:00", $request->end_date ." 23:59:59");
} else {
// default load page - today
$dateScope = array($start_date, $end_date);
};
$dbTimeZone = 'Asia/Kolkata'; // update with your db timezone
$userTimeZone = 'Europe/Sofia';
$dateScope = array_map(function($date) use ($dbTimeZone, $userTimeZone) {
return Carbon::createFromFormat('d-m-Y H:i:s', $date, $dbTimeZone)->setTimezone($userTimeZone);
}, $dateScope);
$students = MeasCanal::whereBetween('recordtime', $dateScope)
->selectRaw('recordtime')
->selectRaw('max(formattedvalue) filter (where fullname = \'Данни.Кота\') as iazovir')
->selectRaw('max(formattedvalue) filter (where fullname = \'Данни.Температура\') as temperatura350')
->where(function ($query) {
$query->where('fullname', 'like', "Язовир.Данни.Кота")
->orWhere('fullname', 'like', "ГСК_11_350.Данни.Температура");
})
->groupBy('recordtime')
->orderBy('recordtime')
->get();
return response()->json($students);
}
return response()->json($students);
}
Note that:- add the following line to the controller if you are not using carbon til yet.
use Carbon\Carbon;
The problem was that date separator was different on each fuction causing Unexpected data found.. After edit him the answer of Sachin Kumar did the job. Thanks for that.
Just discover the problem with similar long way solution:
$start_date0 = date('d-m-Y 00:00:00');
$end_date0 = date('d-m-Y 23:59:59');
$start_date = Carbon::createFromFormat('d-m-Y H:i:s', $start_date0, 'Europe/Sofia')->setTimezone('UTC');
$end_date = Carbon::createFromFormat('d-m-Y H:i:s', $end_date0, 'Europe/Sofia')->setTimezone('UTC');
if($request->start_date != '' && $request->end_date != '')
{
// if user fill dates
$start_date0 = $request->start_date;
$end_date0 = $request->end_date;
$start_date = Carbon::createFromFormat('d/m/Y H:i:s', $start_date0, 'Europe/Sofia')->setTimezone('UTC');
$end_date = Carbon::createFromFormat('d/m/Y H:i:s', $end_date0, 'Europe/Sofia')->setTimezone('UTC');
$dateScope = array($start_date, $end_date);
} else {
// default load page - today
$dateScope = array($start_date, $end_date);
};

How to fix the error in codeigniter project?

My error message in codeigniter framework:
A Database Error Occurred
Error Number: 1140
In aggregated query without GROUP BY, expression #1 of SELECT list contains nonaggregated column 'hms.rooms.id'; this is incompatible with sql_mode=only_full_group_by
SELECT `rooms`.*, count(room_no) as total_rooms FROM `rooms` WHERE `room_type_id` = '10'
Filename: D:/Installed_Apps/OpenServer/OpenServer/domains/hms.loc/system/database/DB_driver.php
Line Number: 691
Why is there such an error and how to eliminate it? In what there can be a problem in the code?
In these functions, something is wrong or everything is normal?
function check_availability($check_in,$check_out,$adults,$kids,$room_type_id){
$query = '?date_from='.$check_in.'&date_to='.$check_out.'&adults='.$adults.'&kids='.$kids.'&room_type=';
$CI =& get_instance();
if($check_in==$check_out){
$check_out = date('Y-m-d', strtotime($check_out.'+ 1 day'));
}
$CI->db->where('id',1);
$settings = $CI->db->get('settings')->row_array();
$CI->db->where('id',$room_type_id);
$CI->db->select('room_types.*,base_price as price');
$room_type = $CI->db->get('room_types')->row_array();
//echo '<pre>'; print_r($room_type);die;
$CI->db->where('room_type_id',$room_type_id);
$CI->db->select('rooms.*,count(room_no) as total_rooms');
$rooms = $CI->db->get('rooms')->row_array();
$total_rooms = $rooms['total_rooms'];
//echo '<pre>'; print_r($rooms);die;
$begin = new DateTime($check_in);
$end = new DateTime($check_out);
$interval = DateInterval::createFromDateString('1 day');
$period = new DatePeriod($begin, $interval, $end);
foreach($period as $dt){
$date = $dt->format( "Y-m-d" );
$dayno = $dt->format( "N" );
$day = $dt->format( "D" );
$day = strtolower($day);
///echo $date;die;
//check for room block period
if($date >= $settings['room_block_start_date'] && $date <=$settings['room_block_end_date'])
{
$block_message = "Sorry.. No Room Available Between ".date('d/m/Y',strtotime($settings['room_block_start_date']))." to ".date('d/m/Y',strtotime($settings['room_block_end_date']))." ";
$CI->session->set_flashdata('error', $block_message);
redirect('');
}
$CI->db->where('O.room_type_id',$room_type_id);
$CI->db->where('R.date',$date);
$CI->db->select('R.*,');
$CI->db->join('orders O', 'O.id = R.order_id', 'LEFT');
$orders = $CI->db->get('rel_orders_prices R')->result_array();
//echo '<pre>'; print_r($orders);die;
//echo $total_rooms;die;
if($total_rooms > 0){
//echo count($orders);die;
if(count($orders) >= $total_rooms){
$CI->session->unset_userdata('booking_data');
$CI->session->unset_userdata('coupon_data');
$CI->session->set_flashdata('error', "Sorry.. This Dates Between Rooms Not Available Please Try With Another Date Or Room");
redirect('front/book/index'.$query);
}else{
continue; // continue loop
}
}else{
$CI->session->unset_userdata('booking_data');
$CI->session->unset_userdata('coupon_data');
$CI->session->set_flashdata('error', "Sorry.. This Dates Between Rooms Not Available Please Try With Another Date Or Room");
redirect('front/book/index'.$query);
}
}
return;
}
function check_availability_ajax($check_in,$check_out,$adults,$kids,$room_type_id){
$query = '?date_from='.$check_in.'&date_to='.$check_out.'&adults='.$adults.'&kids='.$kids.'&room_type=';
$CI =& get_instance();
if($check_in==$check_out){
$check_out = date('Y-m-d', strtotime($check_out.'+ 1 day'));
}
$CI->db->where('id',1);
$settings = $CI->db->get('settings')->row_array();
$CI->db->where('id',$room_type_id);
$CI->db->select('room_types.*,base_price as price');
$room_type = $CI->db->get('room_types')->row_array();
//echo '<pre>'; print_r($room_type);die;
$CI->db->where('room_type_id',$room_type_id);
$CI->db->select('rooms.*,count(room_no) as total_rooms');
$rooms = $CI->db->get('rooms')->row_array();
$total_rooms = $rooms['total_rooms'];
//echo '<pre>'; print_r($rooms);die;
$begin = new DateTime($check_in);
$end = new DateTime($check_out);
$interval = DateInterval::createFromDateString('1 day');
$period = new DatePeriod($begin, $interval, $end);
foreach($period as $dt){
$date = $dt->format( "Y-m-d" );
$dayno = $dt->format( "N" );
$day = $dt->format( "D" );
$day = strtolower($day);
if($date >= $settings['room_block_start_date'] && $date <=$settings['room_block_end_date'])
{
$block_message = "Sorry.. No Room Available Between ".date('d/m/Y',strtotime($settings['room_block_start_date']))." to ".date('d/m/Y',strtotime($settings['room_block_end_date']))." ";
return $block_message;
}
$CI->db->where('O.room_type_id',$room_type_id);
$CI->db->where('R.date',$date);
$CI->db->select('R.*,');
$CI->db->join('orders O', 'O.id = R.order_id', 'LEFT');
$orders = $CI->db->get('rel_orders_prices R')->result_array();
//echo $total_rooms;die;
if($total_rooms > 0){
if(count($orders) > $total_rooms){
$CI->session->unset_userdata('booking_data');
$CI->session->unset_userdata('coupon_data');
return 'Sorry.. This Dates Between Rooms Not Available Please Try With Another Date Or Room';
}else{
continue; // continue loop
}
}else{
$CI->session->unset_userdata('booking_data');
$CI->session->unset_userdata('coupon_data');
return 'Sorry.. This Dates Between Rooms Not Available Please Try With Another Date Or Room';
}
}
return 1;
}
Here is my Book.php controller code where I use that functions:
function index()
{
//echo '<pre>'; print_r($_GET);
//check availbilty
//get_invoice_number();
$this->session->unset_userdata('booking_data');
$this->session->unset_userdata('coupon_data');
$data['page_title'] = lang('make_reservation');
$data['meta_description'] = $this->setting->meta_description;
$data['meta_keywords'] = $this->setting->meta_keywords;
$data['banners'] = $this->homepage_model->get_banners();
$data['testimonials'] = $this->homepage_model->get_testimonials(); // get 6 testimonials
$data['room_types'] = $this->homepage_model->get_room_types_all();
$data['taxes'] = $this->homepage_model->get_taxes();
if(!empty($_GET['room_type'])){
$data['services'] = $this->homepage_model->get_paid_services($_GET['room_type']);
}
//echo '<pre>'; print_r($data['services']);
if(empty($_GET['room_type'])){
$this->render('book/room_types', $data);
}else{
check_availability($_GET['date_from'],$_GET['date_to'],$_GET['adults'],$_GET['kids'],$_GET['room_type']);
$data['room_type'] = $this->homepage_model->get_room_type($_GET['room_type']);
$this->render('book/view', $data);
}
}
you are facing this problem because of the ONLY_FULL_GROUP_BY option in the MYSQL so kindly set,
SET GLOBAL sql_mode=(SELECT REPLACE(##sql_mode,'ONLY_FULL_GROUP_BY',''));
to solve the issue.
SQL query including aggregate functions like COUNT() or SUM() etc. always have a GROUP BY clause in it. Which specifies the other non-grouped columns in the final resultset.
In you query the following remarks are noted:
You have specified rooms.* which is not recommended while grouping.
You may mention specific columns while grouping, and specify those columns in the GROUP BY clause too.
For example,
SELECT
Count(product_tb.product_id),
product_tb.`name`,
product_tb.details
FROM
`product_tb`
WHERE
product_tb.product_id = 1
GROUP BY
product_tb.`name`,
product_tb.details

Calculate date before n days of a month

How to calculate a date before 10 days of every month end ?Am using codeigniter platform.
I need to check whether a date is within 10 days before the end of every month.
Please help
You can try using date_modify function for example see this php documentation
http://php.net/manual/en/datetime.modify.php
i need to check whether a date is within10 days before the end of a month
function testDate($date) {
$uDate = strtotime($date);
return date("m", $uDate) != date("m", strtotime("+10 days", $uDate));
}
echo testDate("2016-03-07") ? "Yes" :"No"; // No
echo testDate("2016-03-27") ? "Yes" :"No"; // Yes
you can create a library with this
class Calculate_days{
function __construct() {
parent::__construct();
}
function calculate( $to_day = date("j") ){
$days_month = date("t");
$result = (int) $days_month - $to_day;
if( $result <= 10){
$result = array("type" => TRUE, "missing" => $result . 'days');
return $result;
}
else{
$result = array("type" => FASLE, "missing" => $result . 'days');
return $result;
}
}
}
controller.php
function do_somthing(){
$this->load->library('Calculate_days');
$result = $this->Calculate_days->calculate(date("j"));
var_dump($result);
}

Get month in date from database

How can I get the month and year of the results of post data from database?
This data i want to retrieve from database is 2016-03-11
My code inside the controller:
public function report(){
$nomor = $this->input->post('nomor_reseller');
$bulan = $this->input->post('month'); //with format YYYY-MM
$report_data = $this->hasil_m->get($nomor,$bulan);
}
My code in model:
function get($nomor,$bulan) {
$this->db->where('nomor_reseller',);
$this->db->where('tgl_pembelian',);
$this->db->select('*');
$this->db->from('tb_pelanggan');
$this->db->join('tb_anggota', 'tb_anggota.id_koperasi = tb_pelanggan.id_koperasi');
$this->db->order_by("tgl_pembelian","DESC");
$this->db->group_by('nomor_reseller');
$query = $this->db->get ();
if ($query->num_rows() > 0) {
return $query->result();
} else {
return false;
}
}
What i want to do is get 2016-03, using $this->db->where.
You might try:
echo date('Y-m', strtotime($date));

Laravel 5 ORM update request, like date_add

I beg to excuse me for my poor english.
So, I have Laravel 5 ORM, and i need to make request that should add date to some rows, like MySQL DATE_ADD. Input is single date interval and array of id's, output is rows of database, that was changed by adding date interval. Ideally, it should be one ORM request. I know that it is possible to use "bad" way and get all rows, update it in a code, and insert to database, but imho it's not good.
I hope answer will be link to some help site or some code if it's does not complicate you. Thanks for your attention!
public function update($id)
{
$user_id = Auth::user()->id;
$rep_task = RepTask::find($id);
$cl_task = \Request::has('json') ? json_decode(\Request::input('json'),true) : \Request::all();
$ids = [];
$task_id = $rep_task->task_id;
$rep_tasks = RepTask::where('task_id', '=', $task_id)
->select('id')
->get();
$new_date = date_create_from_format(self::DATE_FULLCALENDAR_FORMAT, $cl_task['new_date']);
$selected_task_date = date_create_from_format(self::DATE_MYSQL_FORMAT, $rep_task->start_date);
$diff = date_diff($selected_task_date, $new_date);
if(\Request::has('json'))
{
$ids = [1,2,3]; //this for easy understanding
DB::table('rep_task')
->whereIn('id', $ids)
->update(['start_date' => DB::raw('DATE_ADD(start_date, INTERVAL ' . $diff->d . ' DAY)')]);
$out_json = ['updated' => $ids];
return json_encode($out_json, JSON_UNESCAPED_UNICODE);
}
else
{
$start_date = 0;
$end_date = 0;
if (!isset($cl_task['name']) || !isset($cl_task['text']))
return "{'error':'columns are not defined'}";
if (isset($cl_task['start_date']) && isset($cl_task['end_date']))
{
$dt = date_create_from_format(self::DATE_FULLCALENDAR_FORMAT, $cl_task['start_date']);
$start_date = $dt->format(self::DATE_MYSQL_FORMAT);
$dt = date_create_from_format(self::DATE_FULLCALENDAR_FORMAT,$cl_task['end_date']);
$end_date = $dt->format(self::DATE_MYSQL_FORMAT);
}
$rep_task->name = $cl_task['name'];
$rep_task->text = $cl_task['text'];
$rep_task->start_date = $start_date;
$rep_task->end_date = $end_date;
$rep_task->users_id = $user_id;
$rep_task->save();
}
$user_id = Auth::user()->id;
$tasks = Task::getAllTasksByUserFullcalendar($user_id);
return view(
'task.index',
[
'tasks' => $tasks
]
);
}

Categories