I have a table that looks like this
the column date
contains different dates in the range (2015-2009). Is it possible to use one query to retrieve data like this?
Here [2015] - is year that has an array. [01]=>'12', [01] os the month and 12 number of articles in this month i.e.
Provided the date
field is actually a date, this should work:
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT date_format(`date`, \"%Y-%m\") as YearMonth, count(*) as cnt " .
"FROM someTable " .
"GROUP BY YearMonth " .
"ORDER BY YearMonth ";
$data = array();
$result = $conn->query($sql);
if ($result->num_rows > 0) {
$currentYear = "";
while($row = $result->fetch_assoc()) {
$rowYear = substr($row["YearMonth"], 0, 4);
$rowMonth = substr($row["YearMonth"], 5, 2);
if ($rowYear != $currentYear) {
$currentYear = $rowYear;
$data[$currentYear] = array();
}
$data[$currentYear][$rowMonth] = $row["cnt"];
}
}
$conn->close();
print_r($data);
Thx you all, I found a solution to my question, here is the query
str = "SELECT YEAR(date) AS year,MONTH(date) AS month,count(url) AS qtt FROM news GROUP BY date_format(date,'%Y-%m');";
the array $data looks like this
Array
(
[0] => Array
(
[year] => 2009
[month] => 12
[qtt] => 7
)
[1] => Array
(
[year] => 2010
[month] => 1
[qtt] => 31
)
[2] => Array
(
[year] => 2010
[month] => 2
[qtt] => 13
)
)
Then I use foreach loop to convert to a needed array
$group = array();
foreach ($data as $value ) {
$group[$value['year']][$value['month']] = $value['qtt'];
}
The result is
Array
(
[2009] => Array
(
[12] => 7
)
[2010] => Array
(
[1] => 31
[2] => 13
[11] => 15
[12] => 24
)
[2011] => Array
(
[9] => 22
[10] => 31
[11] => 15
)
[2012] => Array
(
[7] => 12
[8] => 31
[9] => 8
)
)
This is what I needed, Each array has year as its name that contains an array which has months as keys and number of sposts in this month as values