I have a query which returns 3 fields, one of which is the month as a two digit number.
I want to basically have it so if month == 1 output january, if month == 02 output febuary etc
This is what I am trying, but this does not work at all, and prevent the entire column from being displayed in PHP.
while ($row = mysql_fetch_array($sqlstr)) {
if ($row['theMonth']=="6") {
echo "<td>{June}</td>";}
echo "<td>{$row['sumSales']}</td>";
echo "<td>{$row['sumPurchases']}</td>";
echo "</tr>";
}
}
What is the correct way to do what I want, and why is what I am doing wrong?
The SQL query I am using is:
SELECT theMonth, sum(Sales) as sumSales, sum(Purchases) as sumPurchases
FROM
( SELECT date_format(saledate, '%Y-%m') AS theMonth, sales.cost as Sales, 0 AS Purchases
FROM sales, products
WHERE sales.product=products.name AND category='Food' OR category='Bocas'
OR category='Bebidas' OR category='Flor de cana por botellas'
OR category='Vino por botella' OR category='hora feliz'
UNION ALL
SELECT date_format(purchasedate, '%Y-%m') AS theMonth, 0 as Sales, purchases.cost as Purchases
FROM purchases
) AS all_costs
group by theMonth
I don´t think I could just replace
SELECT date_format(purchasedate, '%Y-%m') AS theMonth
with
SELECT MONTHNAME(purchasedate) AS theMonth
So what would be the best way to return the month name as text in SQL?
In your SQL you can use
DATE_FORMATto convert a date to a month name:The list of allowable specifiers can be found in the MySQL documentation.
(MONTHNAME should also work too.)
The reason why your current method doesn’t work is because you are currently outputting both the year and the month (e.g. “2010-06”) and this string doesn’t compare equal to the string “6”.