I need to echoing all authors with articles older than 11 months.
But there is nothing as result.
My date column is like this - 2017-07-01 05:00:00
$d = date("F 1, Y", strtotime("-11 months"));
// also tried:
$d = mktime(0, 0, 0, date('n')-11, 1, date('y'));
$items = '';
$sql = "select * from posts where date < " . $d;
$st = $db->prepare($sql);
$db -> execute();
while ($row = $st->fetch()) {
$items .= "<div class='auth'>" . $row['auth'] . "</div>/n";
}
echo $items;
Here a query that returns a distinct list of authors with books published more than 11 months ago.
SELECT DISTINCT AUTH
FROM posts
WHERE `date`<DATE(NOW() - INTERVAL 11 MONTH);
Try this query in your PHP code:
$sql = "SELECT * FROM posts WHERE YEAR(date) = YEAR(CURRENT_DATE - INTERVAL 11 MONTH) AND MONTH(date) = MONTH(CURRENT_DATE - INTERVAL 11 MONTH)";
Related
This question already has answers here:
How do I query between two dates using MySQL?
(12 answers)
Closed 6 years ago.
I am trying to fetch some data from database based on user entered month and year and table name.
From month and year I calculate from_date and to_date
but query is not working if I put dates between $from_date and $todate.
$tableName = $_REQUEST['tableName'];
$month = $_REQUEST['monthName'];
$year = $_REQUEST['yearName'];
// echo json_encode($tableName);
$tableName = json_encode($tableName);
//echo $tableName;
$from_date = date('Y-m-d',strtotime($year."-".$month."-01"));
//echo json_encode($from_date);
//$to_date = date('Y-m-d',strtotime($year."-".$month."-01"));
$to_date = date('Y-m-t', strtotime($from_date));
//echo json_encode($to_date);
$conn = new PDO("sqlite:../../assets/rule_data.db");
$conn->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
//$sqlQuery = "select * from $tableName WHERE date >= '".$from_date."' AND date <= '".$to_date."' ";
//$sqlQuery = "SELECT * FROM $tableName WHERE v_cr_sysdate >= '".$from_date."' AND v_cr_sysdate <= '".$to_date."' ";
//$sqlQuery = "SELECT * FROM $tableName";
//$sqlQuery = "select * from $tableName WHERE date >= '".convert('$from_date','%d-%m-%y')."' AND date <= '".date($to_date)."' ";
$sqlQuery = "select * from $tableName WHERE date between '". date('Y-m-d', strtotime($from_date))."' ";
$sqlQuery .= " AND date <='". date('Y-m-d', strtotime($to_date))."' ";
$query = $conn->query($sqlQuery);
echo json_encode($query);
echo json_encode(["riskModules"=>$query->fetchAll(PDO::FETCH_ASSOC)]);
If I remove AND consition and keep only where date >= '$from_date' It will work but not with date range of from and to date.
Please help where I am wrong in giving AND query to where clasuse.
You can use BETWEEN clause to replace a combination of "greater than
equal AND less than equal" conditions.
Changes
$sqlQuery = "select * from $tableName WHERE date between '". date('Y-m-d', strtotime($from_date))."' ";
$sqlQuery .= " AND '". date('Y-m-d', strtotime($to_date))."' ";
(OR) Which Is Similar As
$sqlQuery = "select * from $tableName WHERE date >= '". date('Y-m-d', strtotime($from_date))."' ";
$sqlQuery .= " AND date <= '". date('Y-m-d', strtotime($to_date))."' ";
Syntax
SELECT column_name(s)
FROM table_name
WHERE column_name BETWEEN value1 AND value2;
Quick Links
mysql-between-clause
The SQL BETWEEN Operator
I'm am writing a PHP program that will get all of the dates for the current work week (excluding Monday). My code is as follows:
//Get Year
$sql = "SELECT YEAR(CURDATE()) AS CurYear";
$result = mysqli_query($db, $sql);
$row = mysqli_fetch_array($result,MYSQLI_ASSOC);
$curyear = $row['CurYear'];
//Get Week
$sql = "SELECT WEEK(CURDATE()) AS CurWeek";
$result = mysqli_query($db, $sql);
$row = mysqli_fetch_array($result,MYSQLI_ASSOC);
$curweek = $row['CurWeek'];
//Get Date of Tuesday
$sql = "SELECT STR_TO_DATE('$curyear$curweek Tuesday', '%X%V %W') AS TueDate";
$result = mysqli_query($db, $sql);
$row = mysqli_fetch_array($result,MYSQLI_ASSOC);
$tuedate = $row['TueDate'];
It works and will return the date of this Tuesday, but is there a more efficient way of doing this, and moreover doing it for the following 3 days?
As explained here: How to find the day of week from a date using PHP?
you can use the date command:
$time = time(); // present time
$day = 3; //the day of the week we are looking for 0: sunday, 1 monday and so on
$dayofweek = date('w', $time); //current day week number
$result = date('Y-m-d', strtotime(($day - $dayofweek).' day', $time));
I'm not sure if you have a requirement of using MySQL, but I would do this in PHP directly. Below is a sample of how you could approach it. Once the variable $TuesTS is set, you can figure out the next day by adding (24*60*60) or 86400 to it, which is the number of seconds in a day.
<?php
$ts = time();
$todayNum = date('N');
if ( ($todayNum >= 2) && ($todayNum<=5)){
$offset = $todayNum - 2; // number of days after Tuesday;
$TuesTS = $ts-($offset*24*60*60);
echo "Tuesday : ".date('Y-m-d', $TuesTS);
}
?>
I have created a function to display the dates and the count of posts within those dates to be used as my blog menu, however it only partially works, any help with this would be appreciated.
Function being called:
function displayBlogMenu()
{
blogDBSelect();
$sql = "SELECT datePosted FROM blog_entries";
$results = mysql_query($sql);
while($post = mysql_fetch_array($results))
{
$startDate = date('Y-m-01', strtotime($post['datePosted']));
$endDate = date('Y-m-01', strtotime("+1 month", strtotime($post['datePosted'])));
$sql2 = "SELECT * FROM blog_entries WHERE datePosted >= '$startDate' AND datePosted < '$endDate'";
$results2 = mysql_query($sql2);
$count = mysql_num_rows($results2);
}
echo ''.date('F, Y', strtotime($startDate)).' ('.$count.' Posts)<br>';
}
I want the function to return the date as links such as:
June, 2011 (10 Posts)
July, 2011 (2 Posts)
It looks like you can do that by one single query
SELECT Date_format(dateposted, '%M, %Y'),
COUNT(*) AS cc
FROM blog_entries
GROUP BY YEAR(dateposted),
MONTH(dateposted)
ORDER BY COUNT(*) DESC,
dateposted DESC
I'm trying to select records which have a recdate within the past year
$goodate = date('Y-m-d h:i:s', mktime(0, 0, 0, date("m"), date("d"), date("Y")-1));
$sqlstmt = "SELECT * FROM #__mytable WHERE id=".$uid." AND recdate > ".$goodate.'"' ;
but I'm getting no records.
What am I doing wrong?
$sqlstmt = "SELECT * FROM #__mytable
WHERE id=".$uid."
AND recdate > ADDDATE(CURDATE(), INTERVAL -1 YEAR)";
If you want to do this programmatically, the DateTime object is a great tool.
$date = new DateTime();
$gooddate = $date->sub(DateInterval::createFromDateString('1 year'));
$sql = "SELECT * FROM #__mytable WHERE id=".$uid." AND recdate > ".$goodate->format('Y-m-d').'"';
This is assuming your date field is mysql type DATE. If not, there are similar DateTime methods for outputting unix timestamps, and the format() method accepts any formatting string that date() does.
$sql = "
select *
from #__mytable
where
id = $uid
and
date_format(recdate, '%Y') = date_format(adddate(curdate(), interval -1 year), '%Y')
"
I was wondering what is the best way to write the where statement in PHP where targetDate < Date.Now - HardCodedHours in PHP
If you mean how to do it in an MySQL query:
SELECT * FROM table WHERE targetDate <= date_sub(now(), interval 1 hour);
This will pull "field1" from table "myTable" where a DATETIME column "targetDate" is older than 12 hours.
$hardcodedHours = 12;
$sql = "SELECT field1 FROM myTable WHERE targetDate <= '" . date('Y-m-d H:i:s', strtotime("-$hardcodedHours hours")) . "'";
$result = mysql_query($sql);
$limitTime = time() - $nbHours * 3600;
$query = "SELECT ... WHERE TIMESTAMP(targetDate) < $limitTime;";
Or something like that.