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')");
Related
I want to get date from VARCHAR column.
(eg: 4/14/2018 12:00:00 AM)
How do I display only date
(eg: 4/14/2018)?
SELECT date(created_at) from self_balance
here created_at(varchar)
this returns NULL value
You can run this query to get your output,
SELECT DATE_FORMAT(STR_TO_DATE(created_at, "%Y-%m-%d"), "%Y-%m-%d") FROM
self_balance
First I am matching date format and converting it to date and then formatting.
You can fetch date like a normal string from the database then you need to use strtotime which parses an English textual DateTime into a Unix timestamp. Then you can use
date function which returns the formatted date string. I have passed a static string. You can pass your string variable which you are fetching from the database
$time = strtotime($date_string_from_database);
<?php
$time = strtotime('4/14/2018 12:00:00 AM');
$newformat = date('m/d/Y',$time);
echo $newformat;
?>
You can see the live demo here
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'";
At my current database i use date format yyyy-mm-dd.
If i want to search by DOB then must use format yyyy-mm-dd to match it with default date format.
Is there a way to search DOB from whatever user input wether its dd-mm-yyyy or dd/mm/yyyy or yyyy-mm-dd and give out the result???
$keyword = clean($keyword,1);
$result = $db->query("SELECT name, dob, email FROM user WHERE name LIKE '$keyword%' OR dob LIKE '$keyword%' OR email LIKE '$keyword%'");
if($result){
//echoing the result
}
Not easily. First convert the user input to the correct format before passing it to the SQL query.
For example:
if (preg_match('~([0-9]{2})[-/]([0-9]{2})[-/]([0-9]{4})~', $input, $matches)) {
return $matches[3].'-'.$matches[2].'-'.$matches[1];
} else {
return $input;
}
You could match UNIX Timestamps eg:
$timestamp = strtotime($date)
SELECT * WHERE UNIX_TIMESTAMP(dob) = '$timestamp'
Check http://php.net/manual/en/function.strtotime.php for more info on strtotime()
This will make it easier for checking within a date range.
Yes, you should normalise the result in PHP before passing it to your SQL query.
Your code may look something like this...
$dateForSqlQuery = date('Y-m-d', strtotime($input));
...assuming that strtotime() will correctly handle those variations.
On the other hand, you should really break up the user input into a separate day, month and year input, then generate the string yourself.
You can use strtotime to parse pretty much any (reasonably formatted) date to a timestamp, and from there you can convert to any other format.
For example:
$yyyy_mm_dd = date('Y-m-d', strtotime('02/01/2012'));
It's quite a processor heavy function though, strtotime, so do be sparing!
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.
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;