Search date in mysql date time column - php

I have a table in MYSQL database with a column db_date with type is datetime ex:2016-10-20 01:05:00
I use a PHP code to search different thing the date is one of them for that i use a date picker have the date like this 10/21/2016 m/d/Y
for that i use this to transform this form to the form in database
STR_TO_DATE('".$date."','%m/%d/%Y')
The Problem is that when i use db_date= STR_TO_DATE('".$date."','%m/%d/%Y') it give only the date that have hour and minutes and second 00:00:00
but i want all the date ex: if i choose 10/20/2016 i want all date with different time in database be selected
i tried to use the date function in mysql but i didn't have result
date(STR_TO_DATE('".$date."','%m/%d/%Y'))
And also i tried to use the DATE_FORMAT(STR_TO_DATE('".$date."','%m/%d/%Y'))
and i didn't have a result
the query will be like this $query=SELECT * FROM tbl_staff {$sql}
and this is the code
$q = array();
$sql = "";
if(isset($_POST['txt_date']) && !empty($_POST['txt_date'])){
$date = mysqli_real_escape_string($conn,$_POST['txt_date']);
$q[] = " db_date=STR_TO_DATE('".$date."','%m/%d/%Y') and db_status!='Done' AND db_status!='Cancelled'";
}
How can i solve this problem ?!

First of all you can use format in datapicker to customise the date :
$('#date').datepicker({format: 'yyyy-mm-dd'});
And for your sql query do (use date() for db_date)
$q[] = " DATE(db_date)= $date and db_status!='Done' AND db_status!='Cancelled'";

Related

How to fetch the Data from MySQL Db which is greater than Or equal to Today's date

I want to fetch the Data from MySQL Db which is greater than Or equal to Today's date, In my Db, the date format is in d/m/Y. And I have nearly 50 records which are greater than today's date but it is retrieving only a few records.
<?php
$currentdate = date('Y-m-d');
$date = str_replace('-', '/', $currentdate);
$tdate= date('d/m/Y', strtotime($date));
// $tdate = date("Y/m/d");
echo $query1 = "SELECT * FROM strategic_batch where batch_sdate ='$tdate'";
?>
Please help me if there is another way. I found the other way but the data is not fetching.
<?php
echo SELECT * FROM strategic_batch WHERE batch_sdate >= CURDATE();
?>
My database records. Click here to view
when I try to fetch the data I get only this records. Click here to view
change 'batch_sdate =' to 'batch_sdate >='
The equal sign will check for exact match. Since you want all records greater than or equals to a particular date, you have to use the >= sign.
This will only work if batch_sdate type is date or datetime as mysql would know how to interpret it. If it is a string, it will not work.

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.

between operator for timestamps in mysql query

I have a form to pick up dates from calender. That form will pass start date and end date. My database table stores date in time-stamp format. I have to create a query to pick records from database table between start date and end date. How can I make a query? I have tried the code below, but which is not working.
if(isset($_POST['filter']))
{
$sid=$_POST['sid'];
$start= date("dMY",strtotime($_POST['start']));
$end= date("dMY",strtotime($_POST['end']));
$res=$db->fetchAll("SELECT * FROM `logfile` WHERE `site_id`=".$sid." AND (date('dMY',`timestamp`) BETWEEN $start AND $end)");
}
Any thoughts?
Thanks.
You're forcing PHP and MySQL to do a lot of useless date/time string<->native conversions for no reason.
Why not simply have:
$start = strtotime($_POST['start']);
SELECT ... WHERE `timestamp` BETWEEN FROM_UNIXTIME($start) AND ...
if $_POST['start'] and $_POST['end'] are already in timestamp format, just don't change them. In other case just convert the string in timestamp:
$start = strtotime($_POST['start']); // where $_POST['start'] might be 2012/08/07
$end = strtotime($_POST['end']);
$res=$db->fetchAll("SELECT * FROM logfile WHERE site_id=".$sid." AND date BETWEEN $start AND $end");
As #Matei Mihai said you don't need to convert $_POST['start'] and $_POST['end'] to timestamp format and you must enclose date columns in quotes.
Also you need to convert date in MySQL compatible format like '2012-08-01'.
"SELECT *
FROM `logfile`
WHERE `site_id`=".$sid." AND
(date('dMY',`timestamp`) BETWEEN '$start' AND '$end')");

Looping through dates until a free one is found

I have a function which checks my database to see if a date exists, if it does exist, i want to display the next date which isnt in the database.
Is this possible?
My function returns 1 if there is a date in the database and 0 if there isnt, im using codeigniter, but not using any built in functions.
Its basically an availability checker, it allows us to input many different dates in the database, so calling my function i use
$availcheck = $ci->availability->check_availability_by_date(date('d/m/Y'));
The i use a if statement to check if the first time it runs it returns a value, this is how i have it
if($availcheck > 0){
// loop through the next dates and run the function again to see if it returns 0
} else {
echo 'available now';
}
I guess i would add 1 to the current date, check that one, then add another 1 and check that and so on.
Im just not sure how.
Cheers,
if i understand you correct , your problem is adding the day ?
if so i would suggest using the epoch or unix time
so convert the date to unix time using mktime than just add 1 day in seconds (24*60*60)
and then convert back to d/m/y format.
you can use the date function.
$date = time(); // get current timestamp
while ($availcheck) // while date IS found in database
{
$availcheck = $ci->availability->check_availability_by_date(date('d/m/Y',$date));
$date = $date + (24*60*60); // add one day
}
$date = $date - (24*60*60); // reduce one day
echo date('d/m/Y',$date); // prints the first date that is not in the DB
This SQL code could work for me.
$today = date("Y-m-d"); //today
$sql = "SELECT date FROM calendar WHERE date>'{$today}' AND date<='2100-12-31' AND date='0000-00-00' LIMIT 1";
Since you can't determine the ending date, 2100 could be for testing.

PHP/MySQL: Convert from YYYY-MM-DD to DD Month, YYYY?

I have in a MySQL table a DATE column that represents the date in this format: YYYY-MM-DD.
I wanto to retrieve the date from the database using PHP but display it like this: DD Month, YYYY.
From '2009-04-13' to '13 April, 2009' for example.
Witch is the best way to do it?? ( I know how to get the date from the DB. I only need to know how to convert it)
I also need to display the month names in Spanish. There is a way to do it without translating each month using strplc or something like that??
I'm new to programming, please be detailed.
Thanks!!!
Refer to DATE_FORMAT() function in MySQL. I guess that's the best way for you to do it.
Also, you can make this:
Fetch your date from DB
Use strtotime in PHP, to convert to unix time
Then format the time using date.
By using date() you'll be able to get months names in Spanish when you set your locale in PHP with setlocale.
You could also skip the strtotime() part by using UNIX_TIMESTAMP(date) in your MySql select. But remember that this is a MySQL specific function and may not be be portable in the future.
Execute following MySQL queries:
SET lc_time_names = 'es_ES';
SELECT DATE_FORMAT(t.date,'%e de %M, %Y') FROM your_table t ...
With MySQLi it'll be:
$mysqli->query("SET lc_time_names = 'es_ES'");
$stmt = $mysqli->prepare("SELECT DATE_FORMAT(t.date,'%e de %M, %Y') FROM your_table t ...where id = ?");
...
Another option not yet mentioned:
SQL:
SELECT UNIX_TIMESTAMP(date) FROM table
PHP:
print date('your format', $timestamp_from_the_db);
Personally, I like to use integer data types in MySQL for date storage in the UNIX timestamp format. I leave all the processing of that integer up to PHP. Keeping tables and queries as simple as possible has always served me well. Predominantly, in the code I write, dates have some sort of calculation done to them. This is all done on the PHP side and always in the UNIX timestamp format. Storing or retrieving the dates in anything other than the UNIX timestamp format just means another step for errors to creep in and makes the query less modular. How a date is formatted is best left up until the last minute before it's displayed. It's just my opinion, but unless there are extreme circumstances where you can't process the DB value after extraction, a date shouldn't be formatted SQL-side.
A simplified example:
<?php
$date = now();
$dueDate = $date + 60*60*24*7; // One week from now
$sqlInsert = "INSERT INTO reports SET `dueDate` = $date";
$resInsert = mysql_query( $sqlInsert );
$sqlSelect = "SELECT `dueDate` FROM reports";
$resSelect = mysql_query( $sqlSelect );
$rowSelect = mysql_fetch_array( $resSelect );
$DB_dueDate = $rowSelect['dueDate'];
$daysUntilDue = ( $DB_dueDate - now() ) / 60*60*24;
$formattedDueDate = date( "j F, Y", $DB_dueDate );
?>
The report is due on <?=$formattedDueDate?>. That is <?=$daysUntilDue?> from now.
Simplest way is to use the strtotime() function to normalize the input to UNIX timestamp.
Then use the date() function to output the date in any format you wish. Note that you need to pass the UNIX timestamp as the second argument to date().
This will help you to convert as you want:
$dob ='2009-04-13';
echo date('d M Y', strtotime($dob));
$origDate = "2018-04-20";
$newDate = date("d-m-Y", strtotime($origDate));
echo $newDate;

Categories