views:

53

answers:

2

I'm a novice in PHP & MySQL coding and still working my way through it.. So, little help on this will be much appreciated:

I have a table that keeps record of certain events. Here is how my table looks like:

Id - Event_Name - Event_Date - Event_Charges
---------------------------------------------
1 - Event 1    - 10/10/2010 - $100
2 - Event 2    - 10/31/2010 - $200
3 - Event 3    - 11/12/2010 - $150
4 - Event 4    - 12/01/2010 - $175

The objective here is to List the name of Events and total up the charges for a particular Date range...

My front end form looks like this:

From Date: ____________
To Date: ______________

The user enters these two fields and i'm supposed to List the Events falling in that date range, and total up the charges.

Please note that Event_Date field is not of field type "date" in MySQL.. Should i have the Event_Date field of field type "date".

+1  A: 

In order to use date operations, the event_date data type needs to be one of:

  • DATETIME
  • DATE
  • TIMESTAMP

Once that's in place, you can use:

  SELECT t.event_name,
         SUM(t.event_charges) AS total_charges
    FROM YOUR_TABLE t
   WHERE t.event_date BETWEEN STR_TO_DATE($from_date, '%Y-%m-%d')
                          AND STR_TO_DATE($to_date, '%Y-%m-%d')
GROUP BY t.event_name

...which brings up the issue of you needing to enforce a date format. That's why I provided an example using STR_TO_DATE, so the string from the HTML form is converted into a MySQL DATETIME data type for comparison.

OMG Ponies
Thanks! This worked like a charm, however, i have one more question.. Is it important to use the STR_TO_DATE function, i already have the format taken care in the front end form by JavaScript.. Thanks a lot!
Jasdeep Singh
@Jasdeep Singh: STR_TO_DATE ensures that the value will be converted to a MySQL DATETIME value (assuming the value matches the format specified). Date formats aren't consistent, so I do recommend using it.
OMG Ponies
But how come i get blank output when i use STR_TO_DATE??? and everything is fine when i dont use it?
Jasdeep Singh
To further advance this query, how would i go about if i was to include the search from Two Coloumns?? For eg, two Event_date coloumns as Event_date1 and Event_date2 ??
Jasdeep Singh
@Jasdeep Singh: Please ask that in a new question
OMG Ponies
A: 

Ok, so i did some head banging and this is what i came up with:

SELECT t.event_name, SUM(t.event_charges) AS total_charges FROM YOUR_TABLE t WHERE t.event_date1 BETWEEN STR_TO_DATE($from_date, '%Y-%m-%d') AND STR_TO_DATE($to_date, '%Y-%m-%d') OR t.event_date2 BETWEEN STR_TO_DATE($from_date, '%Y-%m-%d') AND STR_TO_DATE($to_date, '%Y-%m-%d') GROUP BY t.event_name

This works like a charm for my Report! Much thanks!!

Jasdeep Singh