How to fetch blog posts by month using MONTH() in mySQLi - php

I have my datetime going into the DB like this:
$CurrentTime = time();
$DateTime = strftime("%b-%d-%Y %H: %M: %S", $CurrentTime);
In phpMyAdmin it looks like this:
May-15-2018 01: 04: 00
Feb-08-2018 13: 49: 23
etc...
The field is varchar(50)
I'm trying to extract posts from this table based on the month that the post was created.
I have tried the following:
"SELECT * FROM admin_panel WHERE MONTH(datetime) ='2'"
"SELECT * FROM admin_panel WHERE MONTH(STR_TO_DATE(datetime, '%b-%d-%Y %H: %M: %S')) ='2'"
I don't get an error, but nothing is returning. Any ideas on how I can correct this?

You can use MYSQL STR_TO_DATE with MONTH
"SELECT * FROM admin_panel WHERE MONTH(STR_TO_DATE(`datetime`,'%b-%e-%Y %H:%i:%s')) = 5"
Adding Year with AND condition
SELECT * FROM admin_panel WHERE MONTH(STR_TO_DATE(`datetime`,'%b-%e-%Y %H:%i:%s')) = 5 AND YEAR(STR_TO_DATE(`datetime`,'%b-%e-%Y %H:%i:%s')) = 2018

The following works when the 'datetime' column is defined as DATETIME, yyyy-mm-dd h:i:s (2018-06-14 14:29:15) and not as VARCHAR,
SELECT * FROM admin_panel where extract(month from datetime)='02'
I think, if you use a VARCHAR instead of a DATE.. type, then you will have to typecast string to a date for performing any date-based functions on it in a query. Imo, it is better to have date stored in DATE.. format and let MySQL store it in some format; but you could format it using DATE_FORMAT functions for displaying.
When column type is DATETIME, month() call also can be used as in,
SELECT * FROM admin_panel WHERE month(datetime)='02'

Related

PHP: Search MYSQL database between datetime but use the date only?

I have a column in MYSQL that stores the datetime like so:
2017-08-18 08:59:53
2017-08-18 07:59:00
I can search the database and return the results between the datetime column like so:
$from = date("Y-m-d H:i:s", strtotime($_GET['from']));
$to = date("Y-m-d H:i:s", strtotime($_GET['to']));
$sql1="SELECT * FROM `Table` WHERE mydate>='$to' and mydate<='$from'";
This works fine as long as I search like this:
2017-08-18 08:59:53
But what I need to be able to do is to search like this:
2017-08-18
and still get the same result when I search.
I don't want to use the time in my search string/query.
Try mysql date() function like:
$sql1="SELECT * FROM `Table` WHERE date(mydate)>='$to' and date(mydate)<='$from'";
mysql date() function returns only date part from datetime column in default Y-m-d format.
You are very close. If you want to search a DATETIME or other datestamp column for matches to a particular day, do this:
WHERE mydate >= DATE(whatever_first_day)
AND mydate < DATE(whatever_last_day) + INTERVAL 1 DAY
This searches for everything on the date mentioned in whatever_first_day, starting with midnight on that date, and everything up to, but not including (<), midnight on the day after whatever_last_day.
This way of searching is sargable: it can use an index on the mydate column.
You could also use
WHERE DATE(mydate) >= DATE(whatever_first_day)
AND DATE(mydate) <= DATE(whatever_last_day)
but that is not sargable.
"SELECT * FROM `Table` WHERE date_format(mydate,"%Y-%m-%d")>='$to' and date_format(mydate,"%Y-%m-%d")<='$from'";

SELECT datetime equals today in PHP MySQL

I want to select everything where datetime field in MySQL equals today.
So the datetime field is like this: 2017-03-22 10:11:45
here is what I have:
$stmt = $dbh->prepare("SELECT * FROM list WHERE date_and_time = :date_and_time");
$stmt->bindParam(':date_and_time', $today???);
$stmt->execute();
how can i select the rows in my table where date_and_time equals today?
If you're just looking for today, you don't need to pass anything in. Just take advantage of MySQL's built-in functions:
$stmt = $dbh->query("SELECT * FROM list WHERE DATE(date_and_time) = CURDATE()");
This will format your date_and_time field to be in a Y-m-d format, and compare it to the current date.

How to fetch record by month in MySQL?

I have stored Date in database in dd-mm-yy format, for example 03-10-2013,
How to search record by month? Month in digit (01 to 12);
I am using currently
$query = "SELECT * FROM data WHERE date LIKE %$month%";
but this not working properly.
I am assuming when you say dates as stored in the database in a format, that they are not stored using a "date" type and instead are using a varchar or char type for the column.
Based on that there are few ways to do this.
Leave the database as it is and convert values on the fly.
SELECT * FROM data WHERE Month(STR_TO_DATE(datestrcolumn, '%d/%m/%Y')) = 5;
Change the type of the column to a "date" type column
SELECT * FROM data WHERE Month(realdatecolumn) = 5;
Change the type of the column to a "date" type column, store a separate column for the month.
UPDATE data set monthcolumn = Month(realdatetimecolumn)
then
SELECT * FROM data WHERE monthcolumn = 5;
Create an index on monthcolumn and this query will be much faster than the other queries if there is a lot of data
Fix the date format in your database structure first, change it to: yyyy-mm-dd
Then change your query statement to:
$query = "SELECT * FROM data WHERE MONTH(`date`) = '$month';
This will select the month as '5' or '11' or '12' which will give duplicates for differing years.
If you need the month with year (to avoid duplicate years):
$query = "SELECT * FROM data WHERE SUBSTR(DATE(`date`),1,7) = SUBSTR(DATE('$month'),1,7);
This will return: '2015-01' or '2014-12'
To get date as '01' or '04' or '12':
$query = "SELECT * FROM data WHERE SUBSTR(DATE(`date`),6,2) = SUBSTR(DATE('$month'),6,2);
Try this...
You could use MySQL MONTH() function
MySQL MONTH() returns the MONTH for the date within a range of 1 to 12 ( January to December). It Returns 0 when MONTH part for the date is 0
4 is april
SELECT * FROM tbl WHERE MONTH( date ) ='4'
You can do like it... as it is not in date format(YYYY-MM-DD)
$q="SELECT * FROM data WHERE MONTH(DATE_FORMAT(STR_TO_DATE(date, '%d-%m-%Y'), '%Y-%m-%d') ) = '$YOUR_SEARCH_MONTH' ";

Get data between two dates with date format unkown

date format: init(11)
date column value: 1421382119
I have managed to get the dates from the table.
$sqllast = $Db1->query("SELECT * FROM table");
while($row = $Db1->fetch_array($sqllast))
{
$date1 = date('Y-m-d', $row['create']);
echo "$date1";
}
Question:
I want to get values from this table using the dates interval. I am not getting idea which format shall I enter the dates.
I have tried y-m-d, d-m-y , but it did not work
I tried this query
SELECT * FROM table WHERE create between '2015-01-1' and '2015-01-30'
Since the column type is int, you have to convert your string dates to ints as well.
Try this:
SELECT * FROM `table` WHERE `create` BETWEEN UNIX_TIMESTAMP('2015-01-01') AND UNIX_TIMESTAMP('2015-01-30')
Since you are storing a unix_timestamp as your value in column create, you will want to use MySQLs UNIX_TIMESTAMP() to covert your dates to a unix_timestamp
SELECT * FROM table WHERE create between UNIX_TIMESTAMP('2015-01-1') and UNIX_TIMESTAMP('2015-01-30')`?

Using Date functions to pull records from database

I'm truly stumped on something - I have a table in my database with a column called 'today' that has Date and Time records. The column has entries that look like this:
October 25, 2014, 4:58 am
October 25, 2014, 4:36 am
I'm having trouble pulling the rows by date; I think the time stamp is messing with the MySQL query. And I need an SQL query to pull any records where the variable $today matches the date information in the column 'today'. This doesn't work:
$today = date("F j, Y"); // looks like this: October 25, 2014
$result = mysqli_query($link,"SELECT * FROM records WHERE today = $today"); // 'today' represents the column in the table
while($row = mysqli_fetch_array($result)) {
echo var_dump($row);
}
I just get an empty result, I think due to the time stamp. Can someone advise on a better MySQL query that will only grab the rows where $today matches the date in the 'today' column?
Although storing the date and time as string in varchar is not really a good idea, you could still alter your query to match string containing the current date with a LIKE statement:
$result = mysqli_query($link,"SELECT * FROM records WHERE today LIKE '$today%'");
That is just to get your current setup working as a temporary fix but i highly suggest you take a look at datetime and timestamp or similar date types if this is a serious project and not just playing around. with programming.
UPDATE
With a datetime you could get the dates which are the same as today with:
SELECT * FROM `records` WHERE `today` = CURDATE();
with a timestamp you would need to pass it as date so your query would be:
SELECT * FROM `records` WHERE date(`today`) = CURDATE();
You can just use the MySQL date functions:
SELECT *
FROM records
WHERE today = CURRENT_DATE;
If there is a time component on the today column, then the best structure is:
SELECT *
FROM records
WHERE today >= CURRENT_DATE and today < date_add(CURRENT_DATE, interval 1 day)
It's obvious that both dates are not equal. Both dates are treated like text values and are not equal. You need to convert the column containing date in your MySQL query as such:
$result = mysqli_query($link,"SELECT * FROM records WHERE DATE_FORMAT(today, '%F %j, %Y') = $today");
Note that you have to change your column to store values of the type of DATE. Or just use queries as proposed in other answers.

Categories