Query from to date with php in mysql - php

I have a date field in a mysql table formatted like this: Y-m-d.
I want to export every post that has a date between $fromDate and all the way to $toDate
I am sure its easy but now i am totaly blocked from ideas.
I am using codeigniter if that helps.
Best Regards
Audun

Try building a query similar to this and passing it to mysql_query (assuming your date format in $fromDate and $toDate match the date format of your mysql column)
<?
$query="SELECT * FROM table WHERE date BETWEEN '$fromDate' AND '$toDate'";
?>

In CodeIgniter documentation about Active Record at http://www.codeigniter.com/userguide2/database/active_record.html, there is a sub-section with title "$this->db->where();".
You can use comparison signs (like !=, <, >, <= and >=) just after the name of the column on which condition(s) is checked. For instance :
$this->db->where('id <', $id);
$array = array('name !=' => $name, 'id <' => $id, 'date >' => $date);
$this->db->where($array);

Related

CodeIgniter Model Date Range

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.

Select record based on specific date in codeigniter

I am trying to select a record from specified date
$yesterday = date('Y-m-d',strtotime("-1 days"));
$this->db->get_where('tablename', array('postid' => $dailystat['postid'], 'timestamp >=' => $yesterday));
But i am not getting any record even if there are entries in table. I also want to make sure that query select the only record which was created on specified date.
Any help will be appreciated..
$yesterday = date('Y-m-d',strtotime("-1 days"));
$this->db->get_where('tablename', array('postid' => $dailystat['postid'], 'timestamp >=' => $yesterday, 'timestamp <' => date('Y-m-d')));
If you share your table schema and sample data, I can give you correct answer. Still I can guess you are compairing date string with timestamp.
The code $yesterday = date('Y-m-d',strtotime("-1 days")); will return $yesterday value as '2017-04-10'. But actually in your database you are compairing with timestamp field, which hold the timestamp in numeric value.
You can use php strtotime function to convert any date to respective time stamp. strtotime($yesterday).
Correct Code will be :
$yesterday = date('Y-m-d',strtotime("-1 days"));
$this->db->get_where('tablename', array('postid' => $dailystat['postid'], 'timestamp >=' => strtotime($yesterday)));
Again please make sure, your database field timestamp is storing only date in form of timestamp.
Another solution is, you can use mysql date compare functions.

Converting PHP date range to MYSQL individual dates

I have an availability calendar in which I am currently adding in dates one by one, and using a mysql query to determine if there exists a row with a certain date and changing the class of the day to "booked" (Red).
I would like to enter in a range into my form, and process it through php (or mysql) into multiple, individual dates. My date format is M/D/YYYY, or MM/DD/YYYY, both are accepted. Unfortunately, when I built my calendar, I did not use the date format in sql for entries, but used varchar.
Is there a way to enter into my form for example 1/1/2014-1/3/2014 and have php convert that to 1/1/2014, 1/2/2014, 1/3/2014, and then have a mysql INSERT query to insert multiple values at once?
if (empty($_POST) === false && empty($errors) === true) {
$adcp_data = array(
'date' => $_POST['date'],
'customer' => $_POST['customer'],
'notes' => $_POST['notes'],
);
insert_adcp($adcp_data);
header('Location: adcp.php?success');
exit();
the insert_adcp function looks like this:
function insert_adcp ($adcp_data) {
array_walk($adcp_data, 'array_sanitize');
$fields = '`' . implode('`, `', array_keys($adcp_data)) . '`';
$data = '\'' . implode('\', \'', $adcp_data) . '\'';
mysql_query("INSERT INTO `adcp` ($fields) VALUES ($data)");
}
My workaround and last resort will be to add multiple text inputs and just add multiple dates manually so I only have to submit once. But a range is so much faster!
As a last note, if I could have those multiple entries keep the "customer" and "notes" values for each date in the range that would be amazing. I am prepared to lose those fields though to make this work. Thanks
Something like:
$day = new DateTime($_POST['range_start']);
$end = new DateTime($_POST['range_end']);
$all_dates = array();
while ($day <= $end){
$all_dates[] = $day;
$day->add(new DateInterval('P1D'));
}
That will give you an array of DateTime objects each of which represents a day in your range. You can get each object back into a string by calling DateTime::format() and passing 'm/d/Y' as the format string.
As for getting multiple entries into MySQL, the INSERT syntax allows INSERT INTO table (column) VALUES (row1), (row2), ... (rowN)
(this is clearly not not tested or the final code you would use -- just written into this web form from memory ... you'll have to write it out properly with input sanitation and range checking and whatnot.)
Check if the value from the input match your range format, capture the parts and generate the from and to dates.
if (preg_match('%\A(?<fromMonth>\d{1,2})/(?<fromDay>\d{1,2})/(?<fromYear>\d{4})-(?<toMonth>\d{1,2})/(?<toDay>\d{1,2})/(?<toYear>\d{4})\Z%', $str, $res)) {
$dates['from'] = mktime(0, 0, 0, $res['fromMonth'], $res['fromDay'], $res['fromYear']);
$dates['to'] = mktime(0, 0, 0, $res['toMonth'], $res['toDay'], $res['toYear']);
}
Generate the range between from and to dates.
for ($date = $dates['from']; $date <= $dates['to']; $date = strtotime('+1 day', $date) ){
$dates['range'][] = date('m-d-Y', $date);
}
I think, strtotime is more usable for your case. You can found definition at php.net site:
http://php.net/manual/en/function.strtotime.php

laravel-4 how to change date format

I want to insert a date into the clients table my db schema is below, I want to insert them into the start_day and end_day fields.
I have the below in validations in ClientController.php
If I insert a foreign date_format other than the one defined below I am thrown an error, but if I do insert the correct one it reverts to 0000-00-00. But if I change the field type to text for example the date_format is inserted fine.
$rules = array(
'project_name' => 'required',
'project_brief' => 'required',
'start_day' => array('required', 'date_format:"m-d-Y"'),
'end_day' => array('required', 'date_format:"m-d-Y"')
);
I'm not sure where the problem lies to be honest. I've even tried to convert the time doing the below:
$start_day_old = Input::get('start_day');
$start_day = date("d-m-Y", strtotime($start_day_old));
$project = new Project;
$project->start_day = $start_day
$project->save();
However the results were the same. Does anyone know how I can rectify this issue?
You can't insert a date formated as dd-mm-yyyy in mysql's date field, it should be yyyy-mm-dd, so in your code here
$start_day = date("d-m-Y", strtotime($start_day_old));
Change it to
$start_day = date("Y-m-d", strtotime($start_day_old));
So, if a date is 15-10-2010 then it'll become 2010-10-15 and it's a valid date for date field in the mysql database.

PHP to MySQL date formatting issue

I have a PHP/MySQL date formatting problem. Here, i create the date variables:
$checkDate = date("d/m/y H:i", time());
$datestrto = strtotime($checkDate);
Then i insert it to a mysql table with the column Datatype of bigint.
When i then, later on, when i need to echo the date, i use this code:
echo '<td>'.date("d/m/y H:i",$row['f_uploaded_date']).'</td>';
But istead of echo'ing the date in the format D/M/Y H:i, it echo'es the date in the format of m/d/y H:i.
Can anyone explain why this is happening, and how to fix it?
Thank you in advance,
Adam
When you insert it into the MySQL table do it like this:
INSERT INTO yourtable(something,somedate) VALUES('something',str_to_date('".$checkDate."','%d/%m/%y %H:%i'))
and when you pull it out from MySQL then do it like this:
SELECT *,date_format(somedate,'%D/%M/%Y %H:%i') as formateddate from yourtable
then in php you use:
$row['formateddate']
Hope it helps you :)
EDIT:
The complete code:
$ddate = date("d/m/y H:i", time());
$sql = "INSERT INTO files (rowID, file, mimetype, data, uploaded_by, uploaded_date, size, times_downloaded, description) VALUES (NULL, '$fileName', '$fileType', '$content', '$user', str_to_date('".$ddate."','%d/%m/%y %H:%i'), $fileSize, 0, '$description')";
So you convert a unix timestamp into a formatted date string then convert the formatted time string back into a unix timstamp and insert that into your database. Wouldn't it just be simpler to just insert the unix timestamp you got in the first place? Or not even bother with PHP code and
INSERT INTO sometable (id, f_uploaded_date)
VALUES ($id, UNIX_TIMESTAMP(NOW()))
?
I suspect the explicit problem you describe is due to the fact that strtotime expects date strings of format 99/99/9999 to be the american style of mm/dd/yyyy rather than dd/mm/yyyy as used in the UK.
First,
$checkDate = date("d/m/y H:i", time());
$datestrto = strtotime($checkDate);
is quite funny way of assigning time() frunction result to $datestrto variable.
Next, you don't need that variable either, as you just can use unix_timestamp() mysql function in the insert query.
Now to your question.
istead of echo'ing the date in the format D/M/Y H:i, it echo'es the date in the format of m/d/y H:i.
double-check your syntax. there is a typo somewhere.
You can pull a date format from your mysql database and then when converting to a php variable you can use:
$num=mysql_numrows($result);
$i=0;
while ($i <= $num) {
$date=mysql_result($result,$i,"Date");
$date = date('d-m-Y', strtotime($date));
echo $date."<br>";
}
Where $result is your mysql query result and "Date" is the name of the column. However I am unsure of using this method with the time.
--EDIT--
link: http://php.net/manual/en/function.date.php

Categories