i am facing a strange issue, if i am checking the mysql query with PHP then i didn't get the exact result according to mysql query.
But the same query if i run then i get the expected result, here is mysql query:
SELECT id, follow_up_datetime, followed_by, follow_up_status, case_time_zone, description, case_id
FROM case_note
WHERE TYPE LIKE '%follow-up-open%'
AND (
follow_up_datetime LIKE '%2013-01-08%'
OR date( follow_up_datetime ) < '2013-01-08'
)
AND follow_up_status <= '1'
GROUP BY case_id
ORDER BY case_id DESC
LIMIT 0 , 30
the result of this query is :
but when i use the same query with php then i get the the wrong ids:
PHP
//current date is "2013-01-08";
$follow_q = "SELECT id, follow_up_datetime, followed_by, follow_up_status, case_time_zone, description, case_id
FROM case_note
WHERE `type` LIKE '%follow-up-open%'
AND (
follow_up_datetime LIKE '%$current_date%'
OR date(follow_up_datetime) < '$current_date'
)
AND follow_up_status <= '1'
GROUP BY case_id
ORDER BY case_id DESC";
$follow_r = mysql_query($follow_q) or die('Error in Query!<br />' . mysql_error());
this query providing me the id's like 53, 84, 47, 36.
last three id's are correct but the first is not correct. i want first id is 139. Can anyone please help to find out the exact problem?
UPDATE: here i have update the result of id 53
A few tips concerning your query itself:
Your follow_up_datetime should be a type timestamp or datetime
You don't need the LIKE operator in your date condition.
DATE( `follow_up_datetime` ) = '2013-01-08'
OR
DATE( `follow_up_datetime` ) < '2013-01-08'
This can be shortened into
DATE( `follow_up_datetime` ) <= '2013-01-08'
If you always compare to the current date, you can use CURRENT_DATE
DATE( `follow_up_datetime` ) <= CURRENT_DATE
Don't compare a col of type int to a string which will force MySQL to cast all values of the col follow_up_status to string.
`follow_up_status` <= 1
Are you sure you need LIKE for the type condition?
`type` = 'follow_up_open'
Would be much faster.
PHP documentation about the MySQL extension:
This extension is deprecated as of PHP 5.5.0, and will be removed in the future. Instead, the MySQLi or PDO_MySQL extension should be used. See also MySQL: choosing an API guide and related FAQ for more information.
EDIT:
Just realized you GROUP BY case_id.
If both, id 53 and id 139 have the same case_id MySQL needs to know which row can be discarded. If you don't give this information, one of the two rows is discarded more or less randomly.
To work around this problem use a aggregate function. in your case MIN() would deliver the desired result.
The whole query cleaned up using PHP heredoc notation:
$follow_q = <<< EOQ
SELECT
MIN( `id` ) AS `id`,
`follow_up_datetime`,
`followed_by`,
`follow_up_status`,
`case_time_zone`,
`description`,
`case_id`
FROM
`case_note`
WHERE
`type` = 'follow-up-open'
AND
`follow_up_datetime` <= '{$current_date}'
AND
`follow_up_status <= 1
GROUP BY
`case_id`
ORDER BY
`case_id` DESC
EOQ;
The problem can be from follow_up_status <= '1'. If the column is a numeric type, you should pass the value as a number, not string. Try:
follow_up_status <= 1
If it was me I would error_log() the $follow_q variable and then copy and paste that query into MySQL and see if it returns the same or wrong results because maybe your $current_date variable is wrong.
Related
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
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())
iam developing a webSite using php and mysql and am really beginner in this area.. Now iam stuck in a place where i have to check the current date is newer than the date in my database
so i have written a code like this but it's not working
$SQL = "UPDATE adverts SET active='0' WHERE enddate<NOW()";
$result = mysqli_query($con,$SQL);
in the above code 'advert' is my table name and 'enddate' is where the column containing date in database
can anybody please help me?
As Anthony described in comments, it's a good idea to check if your query is working in PHPMyAdmin at all, by going to PHPMyAdmin -> SQL -> Run Query. This way you can distinguish if it's an MySQL Error or an PHP Error.
UPDATE adverts SET active = 0 WHERE ( enddate < NOW() )
I've set active '0' to 0, simply because I believe it'll be an Integer field - secondly, there's a small but important difference in your enddate:
is it a date field or a datetime field? See below:
SELECT NOW(); // You will get 2010-12-09 17:10:18
SELECT CURDATE(); // You will get 2010-12-09
Source: MySQL Curdate() vs now()
You can use affected_rows() to see if you query did work, but just didn't meet any criteria
$sql = "UPDATE adverts SET active = 0 WHERE ( enddate < NOW() )";
$queried = mysqli_query( $con, $sql );
if ( mysqli_affected_rows( $con ) >= 1 ) {
//We know some rows were effected.
}
Did you tried
UPDATE adverts SET active='0' WHERE enddate<DATE(NOW())
also, is it adverts or advert?
Or you can try with CURDATE()
UPDATE adverts SET active='0' WHERE enddate<CURDATE()
im having the table name fiscalyear
These are the columns
id(auto increment)
begin (financial year begin date)
end (financial year end date)
active (either 0(open) or 1(closed))
begin column consists dates like 2012-01-01
end column consists dates like 2013-12-31
i want to get the financial year begin and end date
These are the conditions
which is open i.e 0,
also it should be the last inserted.
Here is the query i tried please update my query according to my conditions
SELECT CONCAT(BEGIN,'/',END) AS YEAR FROM fiscalyear WHERE active='0' ORDER BY `id` DESC LIMIT 1
THE ABOVE QUERY SELECT DATE IN THIS FORMAT: 2012-01-01/2013-12-31 BUT INSTEAD OF THIS I WANT TO PRINT THE SELETED DATE IN THIS FORMAT 2012-13..
If you want the last row, you can order the table in DESC order by id which is auto increment.
SELECT `BEGIN`,`END`
FROM `fiscalyear`
WHERE `active`='0'
ORDER BY `id` DESC
LIMIT 1
It should be noted that BEGIN and END are reserved words in MySQL, and should be represented as fields using "`"
As for printing the date, I recommend PHP class DateTime
About your second question, you can define Begin and End in your database as DateTime (i remember some data type like this was defined in mySQL) and then you can use this function:
/* Analyzes time-date and returns mktime!*/
function analyze_time_date($tdstr)
{
// tdstr : 2010-08-12 11:41:14
// 0000000000111111111
// 0123456789012345678
$year = (int)substr($tdstr,0,4);
$month = (int)substr($tdstr,5,2);
$day = (int)substr($tdstr,8,2);
$hour = (int)substr($tdstr,11,2);
$minute = (int)substr($tdstr,14,2);
$second = (int)substr($tdstr,17,2);
return mktime($hour,$minute,$second,$month,$day,$year);
}
/* */
function format_time_date($tdstr,$format)
{
return date($format,analyze_time_date($tdstr));
}
when you wanna insert a new row to your database you should use 'date time field name' = NOW() in your SQL query.
Order it by the id primary key, and use a LIMIT 1, so you only get the last record. Use the built in DATE_FORMAT to format your date.
SELECT
CONCAT(DATE_FORMAT(`BEGIN`, '%Y'), '-',
DATE_FORMAT(`END`, '%Y')) AS mydates
FROM
`fiscalyear`
WHERE
`active` = 0
ORDER BY
`id` DESC
LIMIT 1
Edit: I changed the query to concat the years so it will output 2012-2013. The result will be in mydates. If you want the end year to be 13 instead of 2013 format, then use %y a lowercase y in the format string.
Here is the query what i need
SELECT
CONCAT(DATE_FORMAT(`BEGIN`, '%Y'), '-',
DATE_FORMAT(`END`, '%y')) AS mydates
FROM
0_fiscal_year
WHERE
closed = 0
ORDER BY
id DESC
LIMIT 1
Okay guys, this probably has an easy answer but has been stumping me for a few hours now.
I am using PHP/HTML to generate a table from a MySQL Table. In the MySQL table (TimeRecords) I have a StartTime and EndTime column. In my SELECT statement I am subtracting the EndTime from the StartTime and aliasing that as TotalHours. Here is my query thus far:
$query = "SELECT *,((EndTime - StartTime)/3600) AS TotalPeriodHours
FROM TimeRecords
WHERE Date
BETWEEN '{$CurrentYear}-{$CurrentMonth}-1'
AND '{$CurrentYear}-{$CurrentMonth}-31'
ORDER BY Date
";
I then loop that through an HTML table. So far so good. What I would like to do is to add up all of the TotalHours and put that into a separate DIV. Any ideas on 1) how to write the select statement and 2) where to call that code from the PHP/HTML?
Thanks in advance!
Try this
$query= "
SELECT ((EndTime - StartTime)/3600) AS Hours, otherFields, ...
FROM TimeRecords
WHERE
Date BETWEEN '{$CurrentYear} - {$CurrentMonth} - 1'
AND '{$CurrentYear}-{$CurrentMonth} - 31' ";
$records =mysql_query($query);
$sum= 0;
while($row=mysql_fetch_array($records))
{
echo"$row['otherFields']";
echo"$row['Hours']";
$sum+=$row['Hours'];
}
echo" Total Hours : $sum ";
Just use a single query with a Sum(). You could also manually calculate it if you're already displaying all rows. (If paginating or using LIMIT, you'll need a separate query like below.)
$query = "
SELECT Sum(((EndTime - StartTime)/3600)) AS SumTotalPeriodHours
FROM TimeRecords
WHERE
Date BETWEEN '{$CurrentYear} - {$CurrentMonth} - 1'
AND '{$CurrentYear}-{$CurrentMonth} - 31'
";
You can do this in the same query if you have a unique id using GROUP BY WITH ROLLUP
$query = "
SELECT unique_id,SUM((EndTime - StartTime)/3600) AS TotalPeriodHours
FROM TimeRecords
WHERE Date BETWEEN '{$CurrentYear}-{$CurrentMonth}-1'
AND '{$CurrentYear}-{$CurrentMonth}-31'
GROUP BY unique_id WITH ROLLUP
ORDER BY Date
";
In this instance the last result from your query with contain NULL and the overall total. If you don't have a unique ID you will need to do it in PHP as per Naveen's answer.
A few comments on your code:
Using SELECT * is not considered good practice. SELECT the columns you need.
Not all months have a day 31 so this may produce unexpected results. If you're using PHP5.3+, you can use
$date = new DateTime();
$endDate = $date->format( 'Y-m-t' );
The "t" flag here gets the last day of that month. See PHP docs for more on DateTime.