Tcz
Tcz

Reputation: 701

PHP&MySQL: issue using php for and mysql query

I would calculate the total profit of a DataBase for each month using 12 different function [one for each month(yes its probably not a nice solution but I am learning step by step )]

This is the .php code (x12 times)

$January="SELECT JanuaryProfit()";     //Function
echo "<b>January Profit: E</b>";
$January = mysql_query($giugno,$conn)
          or die("Query failed: " . mysql_error($conn));
$num_rows=mysql_num_rows($January);

if (! $num_rows)
      echo "<p>0</p>";
else {
      while ($row = mysql_fetch_row($January)) {
            $price=$row[0];
            echo "$price";
      };
}

Function JanuaryProfit() is declared this way [MySQL]:

BEGIN
DECLARE PriceTOT FLOAT;
SELECT SUM(o.PrezzoTot) INTO PriceTOT
FROM orders o
WHERE o.Data BETWEEN '2012-01-01' AND '2012-01-31';
RETURN PriceTOT;
END

And so I've declared singularly february,march,...,december.

I wouldn't paste 12 times the first code into the .php page.I've tried using a for cicle that use different function every time but i cannot figure how to solve this,correctly.Any suggest?

All I wanna do by now is changing the php part only,using a loop.

Upvotes: 0

Views: 73

Answers (1)

Sammitch
Sammitch

Reputation: 32232

Oh my dear, sweet, flying spaghetti monster. Stop whatever you are doing, then burn it, and then use something like the below to avoid writing a function for every month of every year from the beginning of time until the end.

SELECT 
  YEAR(o.Data) as 'year',
  MONTH(o.Data) as 'month',
  SUM(o.PrezzoTot) as 'total'
FROM orders o
GROUP BY YEAR(o.Data), MONTH(o.Data)

I assume at some point you were having difficulty figuring out the last day of the month programmatically, so here's another link to LASTDAY() which is also the documentation page for all of the massively useful date functions.


edit

define('masochism', TRUE);

$ohgodwhy = array('January','February','March','April','May','June','July','August','September','October','November','December');

$aaahhh = 'SELECT %sProfit()';

foreach( $ohgodwhy as $pleaseno ) {
    $itburns = sprintf($aaahhh, $pleaseno);
    $hidethebodies = mysql_query($itburns) or die("Couldn't hide the bodies because: " . mysql_error());
    // etc...
}

Upvotes: 1

Related Questions