CodeIgniter Model Date Range - php

I have been struggling for a few weeks. Recently I posted a question here CodeIgniter Datatables Server Side Date Range using Datepicker but no luck.
Then I decide to isolate the problem by testing the Codeigniter Model and seems like there is a problem there.
Below is the code and image.
Codeigniter Model
function get_allbillinglistByDate($startdate,$enddate){
$data = array();
$sdate = "09/01/2020";
$edate = "11/01/2020";
$this->db->from('invoices');
$multipleWhere = ['invoices.Approved' => 1,'invoices.xero' => 0];
$this->db->where($multipleWhere);
//$this->db->where('Invoice_Date BETWEEN "'. date('m-d-Y', strtotime($sdate)). '" and "'. date('m-d-Y', strtotime($edate)).'"');
$this->db->where('Invoice_Date >=', date('m-d-Y', strtotime($sdate)));
$this->db->where('Invoice_Date <=', date('m-d-Y', strtotime($edate)));
$Q = $this->db->get();
if ($Q->num_rows() > 0){
foreach ($Q->result_array() as $row){
$data[] = $row;
}
}
$Q->free_result();
return $data;
}
Here is the screenshot
Date Column where only 2020 record should show but it shows 2021 too
Not sure where things are going wrong the date Column where only 2020 record should show but it shows 2021 too
Please advise.

Although MySQL tries to interpret values in several formats, date parts must always be given in year-month-day order (for example, '98-09-04'), rather than in the month-day-year or day-month-year orders commonly used elsewhere (for example, '09-04-98', '04-09-98'). To convert strings in other orders to year-month-day order, the STR_TO_DATE() function may be useful.
Ref: https://dev.mysql.com/doc/refman/8.0/en/date-and-time-types.html
So, change your code as below
date('Y-m-d', strtotime($sdate)

The answer of Raj is correct. You can tweak it according to your expected format like below
date('d/m/Y', strtotime($sdate));
date('d/m/Y', strtotime($edate));
An alternative syntax of your method but you may need to tweak it a little. You should format date params and then send them to this method, you can format them as we described
function get_allbillinglistByDate($startdate,$enddate){
$sql = "SELECT * FROM invoices where Approved = 1 AND xero = 0 AND DATE(Invoice_Date) BETWEEN ? AND ?";
$data = array();
array_push($data, $startdate);
array_push($data, $enddate);
$query = $this->db->query($sql, $dataArr);
return (array)$query->result_array();
}
For more info check https://www.php.net/manual/en/function.date.php

ok guys the problem is resolved. I had to change the column type in my MYSQL table in PHPMyAdmin from varchar to date in order to get the date range.

Related

How to compare created_at timestamp with Carbon date In laravel?

I have orders table , I want to get orders that have been created at this month only (delivery process happens at the same day).
I want to compare between the carbon date which refers to this current month with the created_at field of type timestamps for orders.
This is my attempt:
$month = Carbon::today();
$currentMont = $month->month;
$thisMonthOrders = Order::where('place_id',$id)->where('stage',9)->whereDate('created_at',$currentMont)->get();
dd($thisMonthOrders);
The output that it gives me is an empty array.
You'll need to use the MONTH function in MySQL, along with a whereRaw:
$thisMonthOrders = Order::where('place_id',$id)
->where('stage',9)
->whereRaw('MONTH(created_at) = ?',[$currentMont])
->get();
However, you'll have issues when you have multiple years, unless you also add in a YEAR check. You might have better luck with whereBetween instead.
$start = Carbon::now()->startOfMonth();
$end = $start->copy()->endOfMonth();
$thisMonthOrders = Order::where('place_id',$id)
->where('stage',9)
->whereBetween('created_at',[$start, $end])
->get();

how to filter results inside where clause in laravel?

I am new to laravel, I am building a small application which alerts when event date is a week away from current date. Here is my controller code
public function index()
{
$domain_count = domain_details::get()->count();
$domain_alert = domain_details::
where('domain_ex_date','>',date('Y-m-d'))
->get();
}
The domain_ex_date is in the format (YYYY-mm-dd) stored with the help of Carbon. The line where('domain_ex_date','>',date('Y-m-d')) gets me whole record when the domain_ex_date is away from the current date. i.e 2017-06-12 > 2016-09-15 gets the whole record. Here what i want to do is , i want to filter and get the only records which is only a week away from the current date. How do i do this ? i have tried like subweek() and subdays() but nothing helped.
I should get the record only when it satisfies this condition domain_ex_date - current date = 7
You can use strtotime():
domain_details:: where('domain_ex_date','<',date('Y-m-d',strtotime("+7 days")))
-> where('domain_ex_date','>',date('Y-m-d'))
->get();
Use Carbon!
Carbon is a build in date-extension ... Try it! :)
$week = Carbon::now()->addWeek();
$now = Carbon::now();
domain_details::where("domain_ex_date","<" $week)
->where("domain_ex_date", ">" $now)
->get()
Or you could also use the addDays($days) method!
$week = Carbon::now()->addDays(7);
I used carbon and this is what worked well for me
$week = Carbon::now()->subWeek();
$now = Carbon::now();
$domain_count = domain_details::get()->count();
$domain_alert = domain_details::where("domain_ex_date",">", $week)
->where("domain_ex_date", "<" ,$now)
->get();

mysqli prepared statements with between clause

My question is similar to [this][1] but the solution provided there doesn't work for me.
I have a DB and I have one column called birth that contains a date in the format year-day-month 00:00:00. Now I want to extract from the DB all the records which birth is between two dates.
The birth value has been inserted in the DB with this code
$date = $day . "-" . $month. "-" . $year;
$a = strptime($date, '%d-%m-%Y');
$DB_date = date('Y-m-d H:i:s',mktime(0, 0, 0, $a['tm_mon']+1, $a['tm_mday'], $a['tm_year']+1900));
To extract the dates I am using this code:
$stmt = $conn->prepare('SELECT * FROM database WHERE `birth` BETWEEN ? AND ?');
$start_date = '1990-01-01';
$stop_date = '1995-01-01';
$stmt->bind_param('ss',$start_date,$stop_date);
$stmt->execute();
$result = $stmt->get_result();
but it doesn't find anything so $result->num_rows is equal to 0 and it doesn't give any errors so the problem must be in the comparison of the dates.
Birth column format is y-d-m hour min sec. But in your where clause you are ignoring hour minute second factor.
Replace:
$start_date = '1990-01-01';
$stop_date = '1995-01-01';
With this:
$start_date = '1990-01-01 00:00:00';
$stop_date = '1995-01-01 00:00:00';
Kindly try it and let me know if it works
I found the solution
The code in my question works if the data type of the column in the DB is datetime and you also need to make sure that $start_date is older than $stop_date. I still wonder though why it didn't work with the date data type.
I had the same issue. I found another thread with the same problem (not sure how to duplicate this thread) here
However just to sum up,
They managed to get the desired results by bracketing the question marks for the params.
$stmt = $conn->prepare('SELECT * FROM database WHERE `birth` BETWEEN (?) AND (?)');
$start_date = '1990-01-01';
$stop_date = '1995-01-01';
$stmt->bind_param('ss',$start_date,$stop_date);
$stmt->execute();
$result = $stmt->get_result();
Hope this helps.

Trouble inserting a date into a MySql database

I've looked at several of the threads that have to do with this issue and still can't figure out what's going wrong with my code.
I'm bring a date field from my form that is in this format "mm-dd-yyyy", when I bring it to my code to update the date of birth field as "yyyy-dd-mm" I use the following
$birth=$_POST['dateBorn'];
$dateB = date('Y-d-m',strtotime($birth));
$finaldateB = ($dateB === false) ? '0000-00-00' : date('Y-d-m',strtotime($dateB));
When I echo the values of the variables (using a date of birth of 11-23-2012) I see the following values for them birth = 11-23-2012, dateB = 1969-31-12, finaldateB = 1969-31-12
I'm obviously doing something incorrect and haven't been able to locate where
TIA
In order to get things to function, I've at least discovered a work-around that may not be elegant but gives me the results I need for now
$dateB = $birth;
$dateborn_a=explode("-",$birth);
$yearborn = $dateborn_a[2];
$dayborn = $dateborn_a[1];
$monthborn = $dateborn_a[0];
$dateOfBirth=$yearborn."-".$monthborn."-".$dayborn;
And then use the value in $dateOfBirth to update the table. It's worked for all the records I've tested it on so far.
$dateB = date('Y-d-m',strtotime($birth));
here
y is for year
d is for day
m is for month
so formate will be yyyy-dd-mm
try
$dateB = date('Y-m-d',strtotime($birth));
You're using Y-d-m instead of Y-m-d. MySQL's date format should be YEAR-MONTH-DAY. Using
$dateB = date('Y-m-d',strtotime($birth));
should fix it.

PHP - Formatting HH:MM:SS to 12hr HH:MM:a string

I'm hoping this will be a piece of pie for someone! String output is currently 12:00am for everything.
The following code from MySQL with format HH:MM:SS (hours_open, hours_closed)
$get_hours_sql = "SELECT * FROM client_hours ORDER BY day";
$get_hours_res = mysqli_query($dbConnect, $get_hours_sql) or die(mysqli_error($dbConnect));
// Establish the output variable
$hoursList = '<div class="right_bar">';
while ($productList = mysqli_fetch_array($get_hours_res)) {
$id_hours = $productList['id_hours'];
$day = $productList['product_name'];
$open = $productList['hours_open'];
$close = $productList['hours_close'];
$hoursList .= ''.date("g:ia", $open).' - '.date("g:ia", $close).'<br/>';
}
$hoursList .= '</div>';
echo $hoursList;
Output is currently
12:00am - 12:00am
looped.
I want to get the output to
11:00am - 11:00pm
which would represent the database entries.
Thanks!
I always find PHP <-> MySql date handling fiddly (got better with 5.3 though).
My guess is that the mysql query returns the date as a string and date() is expecting a time stamp.
Often, I just get mysql to format the date as a string for me and return it as an additional field, like so:
$get_hours_sql = "SELECT *,date_format(hours_open,'%h:%i %p') as hours_open_formatted, date_format(hours_close,'%h:%i %p') as hours_close_formatted FROM client_hours ORDER BY day";
then just use the formatted fields:
$hoursList .= ''.$productList['hours_open_formatted'].' - '.$productList['hours_close_formatted'].'<br/>';
Data accepts as it's second parameter a Unix timestamp, so what you're trying to do simply won't work. You could use either mysql's TIME_TO_SEC function, or php's mktime to convert the time string to a Unix timestamp.
Example:
$openHours = explode(':',$productList['hours_open']);
$timestamp = mktime($openHours[0],$openHours[1]);
$yourDate = date("g:ia",$timestamp);
Edit: I think you should try Ben's answer, I think it's a better solution than mine.

Categories