How can I show data from a specific mysql month

$query = mysql_query(
         "SELECT id, BuyerName,BuyerEmail,TransactionID,DateTime FROM `order`
         WHERE DateTime="2015 AND 08""; LIMIT $start, $per_page"
         ) 
or die(mysql_error());
Run codeHide result

I am trying to make a request to show a specific month and year.

+4
source share
4 answers

You can use the built-in functions YEARand MONTHMySQL, such as:

SELECT `id`, `BuyerName`,`BuyerEmail`,`TransactionID`,`DateTime`   
FROM `order` WHERE YEAR(DATE(`DateTime`))=2015 AND MONTH(DATE(`DateTime`)) = 8
+2
source

If your column is a data type date, you can use the date range for your criteria in a way Sargable

SELECT id, BuyerName,BuyerEmail,TransactionID,DateTime
 FROM `order` 
WHERE DateTime >='01-08-2015' 
AND  DateTime <= '31-08-2015'

For datetimeyou can write it as

SELECT id, BuyerName,BuyerEmail,TransactionID,DateTime
 FROM `order` 
WHERE DateTime >='01-08-2015 00:00:00' 
AND  DateTime <= '31-08-2015 23:59:59'
0
source

datetime,

$query = mysql_query("
    SELECT id, BuyerName, BuyerEmail, TransactionID, `DateTime` 
    FROM `order` 
    WHERE YEAR(DATE(`DateTime`)) = 2015 AND MONTH(DATE(`DateTime`)) = 8
    LIMIT $start, $per_page
") or die(mysql_error());

$query = mysql_query("
    SELECT id, BuyerName, BuyerEmail, TransactionID, `DateTime` 
    FROM `order` 
    WHERE `DateTime` LIKE '2015-08-%'
    LIMIT $start, $per_page
") or die(mysql_error());
0
$time_you_want_to_choose = strtotime('previous month');

$ym = date('Y-m', $time_you_want_to_choose);

$query = mysql_query("
          SELECT `id`, `BuyerName`, `BuyerEmail` , `TransactionID`, `DateTime` 
          FROM `order` 
          WHERE `DateTime` like '$ym%'
          LIMIT $start, $per_page
         ");
0

Source: https://habr.com/ru/post/1606706/


All Articles