Removing time from a datetime field in a select query - php

I have the following SQL query to use on my website and I want to remove the time from the datetime column 'Date_Required' when the resulting table is displayed:
$query = "SELECT Job_No, Sub_No, Visit_Status, Engineer, CAST(Date_Required AS DATE) FROM dbo.VSMF_SERVICE_VISITS WHERE Visit_Status = 'O' and Engineer='*AY' and Date_Required >= '2018-01-01 00:00:00.000' ORDER BY Date_Required DESC";
So it's displayed as "Jan 01 2018" instead of "Jan 01 2018 12:00:00:000PM"
The query is in a PHP file.

Try this one.
$query = "SELECT CAST(Date_Required AS DATE) as Date_Required FROM dbo.VSMF_SERVICE_VISITS WHERE Visit_Status = 'O' and Engineer='*AY' and Date_Required >= '2018-01-01 00:00:00.000' ORDER BY Date_Required DESC";
I hope this will work for you. If you want to select all the columns in the table then mention them in the select statement one by one like this
SELECT id, name, CAST(Date_Required AS DATE) as Date_Required from ...
using * will be more tricky.

If you are determined to do this in SQL, then have a read of this post (which it took me a couple of seconds to find):
Best approach to remove time part of datetime in SQL Server

If you want to do this with PHP you have several options, cutting the first 10 chars of the string by substr or using the powerful DateTime class
<?php
$dateTime = "2018-03-05 01:30:00";
echo substr($dateTime, 0 , 10);// option 1
echo "\n";
$dateTimeObj = new DateTime($dateTime);// option 2
echo $dateTimeObj->format("Y-m-d");
this outputs
2018-03-05
2018-03-05
live demo

Related

MySql Query for Current Date

I have s MySQL Query where I want to pull data from my database but base it on the current month information
FROM lbs_trace_etrack WHERE (lbs_agent = '$slfirstname' AND DATE (lbs_date) = CURDATE()) ORDER BY lbs_date DESC LIMIT 0,50");
This string pulls out the information for the current day.
I have also tried the below string but get no results from it:
FROM lbs_trace_etrack WHERE (lbs_agent = '$slfirstname' AND MONTH(lbs_date) = (MONTH(NOW()) AND YEAR(lbs_date) = YEAR(NOW())
My table date format is as follow 2016-08-02
Or using PHP variables as so:
<?php
$start = date('Y-m-01'); // FIRST DAY OF CURRENT MONTH
$end = date("Y-m-t", strtotime(date("Y-m-d"))); // LAST DAY OF CURRENT MONTH
$sql = "SELECT * FROM lbs_trace_etrack WHERE lbs_agent = '".$slfirstname."' AND (lbs_date BETWEEN '".$start."' AND '".$end."')";
?>
I have done the following and it works
FROM lbs_trace_etrack WHERE lbs_agent = '$slfirstname' AND MONTH(lbs_date) = MONTH(CURDATE()) AND YEAR(lbs_date) = YEAR(CURDATE()) ORDER BY lbs_date ASC, lbs_time ASC
Thanks to all and Tijo for guidance
Assuming lbs_agent is a DATE field type as mentioned in comments, you could do this (note I am just showing the pertinent date part of your WHERE clause):
WHERE lbs_agent >= DATE_FORMAT(NOW() ,'%Y-%m-01')
It is important that you do not use a function call on the left (field definition) side of the WHERE comparison, as you will then not be able to leverage any index on that field. Doing this would require a full table scan with MySQL performing the function on this field for every row in the table such that the comparison can be made.
Feel free to use MySQL functions for the comparison value, as those would be calculated just once when the query is being planned. You would then be able to use an index on the field for quickly filtering the rows in the table that meet the criteria. From a query execution standpoint, this is basically that same as if your query has this WHERE clause:
WHERE lbs_agent >= '2016-08-01'
This is as compared to the examples in your question which would be executed as:
WHERE DATE(lbs_date) = '2016-08-03'
and
WHERE MONTH(lbs_date) = 8 AND YEAR(lbs_date) = 2016
Both of these would require full table scan since the values derived from the field are not able to be determined until the row is scanned.
You could try to extract the month, such as EXTRACT(MONTH from NOW())
you can use following code if it timestamp
MONTH(CURDATE())

Comparing date() in sql query

I have 5 records in mysql database and these records have recorded date within this date interval.
$year=2015;
$month=8;
$datefrom=1;
$dateto=31;
$startdate='$year-$month-$datefrom 00:00:00';
$enddate='$year-$month-$dateto 23:59:59';
So I write a query to get these records out like this:
$sql = "SELECT id FROM newpost WHERE email=:email AND :startdate <= poststart <= :enddate AND postapproved=1";
Given that poststart column in table newpost has SQL Datetime format like this: "Y-m-d H:i:s".
But when I changed variable $year = 2016, I still got 5 results? It should return no record. Because those 5 records are recorded between 1 - 31 August 2015.
So I thought I did something wrong in the sql query especially the comparing date part but I could not configure out how to fix it?
Please help!
You can use BETWEEN in your query
$sql = "SELECT id FROM newpost WHERE email=:email AND (poststart BETWEEN :startmonth AND :endmonth) postapproved=1"
Use single quotes to wrap your date values
$sql = "SELECT id FROM newpost WHERE email=:email AND poststart BETWEEN ':startdate' AND ':enddate' AND postapproved=1";
A couple quick things to check to make sure it's not a syntactical error:
Your variable names don't match up. You defined startdate and enddate, but then in the query you used startmonth and endmonth.
You should probably also use leading zeros in your month and day, i.e.:
$month='08';
$datefrom='01';

Two appointments a week php

I have the following situation:
A patient is allowed to make 2 online appointments a week from today.
My code is:
$user_id = $_SESSION['id'];
$datum1 = date("d-n-Y");
$datum2 = date("d-n-Y", strtotime(date("Y-m-d", strtotime($datum)) . " +7 days"));
$query = "SELECT * FROM afspraken WHERE user_id='$user_id' AND datum BETWEEN '$datum1' AND '$datum2'";
The query with values:
SELECT * FROM afspraken WHERE user_id='2' AND datum BETWEEN '24-4-2012' AND '01-5-2012'
Still PhpMyAdmin gives 0 results whilst there are more then 10 records.
id user_id datum begintijd opmerking
55 2 24-4-2012 9:30 Deze afspraak is online gemaakt.
56 2 24-4-2012 10:00 Deze afspraak is online gemaakt.
Does someone see whats wrong in my queries?
Thanks in advance.
You can exclude date representation errors by leaving it to MySQL.
$query = "SELECT * FROM afspraken WHERE user_id='$user_id' AND datum BETWEEN CURRENT_DATE AND DATE_ADD(CURRENT_DATE, INTERVAL 1 WEEK)";
In general you probably need format 'YYYY-MM-DD'.
Another thing: your code is vulnerable for SQL injection. Use a prepared statement. They are nicer to read too, and escaping single quotes and backslashes in string fields etcera.
From the MYSQL Doc:
For best results when using BETWEEN with date or time values, use CAST() to explicitly convert the values to the desired data type.
http://dev.mysql.com/doc/refman/5.5/en/comparison-operators.html#operator_between
I would try casting the dates as DATE MySQL datatype in your WHERE clause.
So change you query to:
SELECT * FROM afspraken WHERE user_id='2' AND datum BETWEEN CAST('24-4-2012' AS DATE) AND CAST('01-5-2012' AS DATE);
For first check if in your database the field 'datum' is a date field.
Replace your query like this:
SELECT * FROM afspraken WHERE user_id='2' AND datum BETWEEN '24/4/2012' AND '01/5/2012'

getting current (system) day using an SQL query in PHP

I have this MySQl database that has a table which contains a column that contains days of the week like "Mon", "Tue" etc.
How do I get query the database and match this column content with the current (system) day?
like say
select .... where tablename.columnname = systemday
thanks.
Try using date_format(now(), "%a") as your condition value.
Read more here: http://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html#function_date-format
Haven't you tried searching ?
Anyways i hope you want something like this,
$cur_day= date('D');
select .... where tablename.columnname = $cur_day;
WHERE tablename.columnname = substr(dayname(now()),1,3)
or
WHERE tablename.columnname = date_format(now(),'%a')
Note, however, that it may be affected by locale settings.
http://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html#function_weekday
Returns the weekday index for date (0 = Monday, 1 = Tuesday, … 6 = Sunday).
http://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html#function_dayofweek
Returns the weekday index for date (1 = Sunday, 2 = Monday, …, 7 = Saturday). These index values correspond to the ODBC standard.
Example:
SELECT * FROM mytable WHERE dayOfTheWeek=WEEKDAY(NOW())
Also, you can do this using PHP`s strftime and date functions:
$query1 = mysqli_query('SELECT * FROM mytable WHERE dayOfTheWeek="'.date('N').'"');
$query2 = mysqli_query('SELECT * FROM mytable WHERE dayOfTheWeek="'.strftime('%u').'"');
But, I think, it is better to generate this in PHP-only way.
<?php
$day=date('D');
$sql='select * from the_table where the_table.'.$day.'=systemday';
?>

How to insert and read time/date in MySQL/PHP?

I want to read the single day, month and year, without adding 3 extra MySQL-rows, in this format (with PHP):
day: 01
month: Jan, Feb, Mar..(first three letters)
year: 2011
This is table and PHP script, which I use now:
I add the date with PHP:
mysql_query("INSERT INTO news (...,`time`) VALUES (...'".date(d.".".m.".".Y)."');");
I read it out with:
$query = "SELECT * FROM news";
$result = mysql_query ($query);
while ($row = mysql_fetch_assoc ($result)) {
echo $row['time'];
}
MySQL table:
news:
time(text):
"27.03.2011"
Query should be:
mysql_query("INSERT INTO news (...,`time`) VALUES (...'".date(d.".".M.".".Y)."');");
M instead of m gives you the 3 letter textual representation of the month.
Get it with:
while ($row = mysql_fetch_assoc ($result)) {
echo date( 'd', strtotime( str$row['time'] ) );
echo date( 'M', strtotime( str$row['time'] ) );
echo date( 'Y', strtotime( str$row['time'] ) );
}
Read more on:
http://php.net/manual/en/function.date.php
you can either do it in PHP, check the strftime function or use in SELECT something like
SELECT DAY(date) as day, MONTH(date) as month, YEAR(date) as year FROM table
and in php you would acccess it as $result['day']. $result['month'] etc. the "date" in SELECT query is of course the name of the column in which you store your date. I would recommend strftime
You can use MONTH(), DAY(), YEAR() Mysql functions., i.e,
SELECT MONTH(`time`) AS `month`, DAY(`time`) AS `day`, YEAR(`time`) AS `year` FROM `news` [...]
SELECT *, substring(1,2) as day, substring(4,2) as month, substring(7) as year FROM table
Also you can(and should) use date table format and use DAY(), MONTH(), YEAR() functions
You should be using a DATETIME column in your mysql table. MySQL is then responsible for storing the date in its own internal format, and you can retrieve it in any format you need.
To insert the current date, you can simply
INSERT INTO news (...,`time`) VALUES (...,NOW())
To retrieve it in the format you want, use
SELECT DATE_FORMAT(`time`, '%d.%b.%Y');
Documentation on MySQL DATE_FORMAT()

Categories