Tanya
Tanya

Reputation: 11

Get results from mysql table for specific month, php, mysql

I want to get results from mysql table for specific month. I write query but query not working properly. Can someone help ?

$sql = "SELECT sum(size) as size FROM tb_size WHERE MONTH(date_created) = '" . mysqli_real_escape_string($db, "Oct") . "' AND YEAR(date_created) =   YEAR(CURRENT_DATE()";
$query = mysqli_query($db, $sql);
$result = mysqli_fetch_object($query);
$size = $result->size;
echo $size;

Upvotes: 0

Views: 273

Answers (2)

Jameson the dog
Jameson the dog

Reputation: 1806

as stated - Month returns a number: https://www.w3resource.com/mysql/date-and-time-functions/mysql-month-function.php

you could use MonthName: https://www.w3resource.com/mysql/date-and-time-functions/mysql-monthname-function.php but that returns a full name (October) and not Oct like you're using.

you could also use DATE_FORMAT(date_created, '%b')to get the short month name

Upvotes: 0

Gordon Linoff
Gordon Linoff

Reputation: 1271211

MONTH() returns a number. So your query should like like this:

SELECT sum(size) as size
FROM tb_size
WHERE MONTH(date_created) = 10 AND YEAR(date_created) = YEAR(CURRENT_DATE();

If you want Oct to match, you can use DATE_FORMAT() instead:

SELECT sum(size) as size
FROM tb_size
WHERE DATE_FORMAT(date_created, '%b') = 'Oct' AND YEAR(date_created) = YEAR(CURRENT_DATE();

Upvotes: 1

Related Questions