Splitting into quarter with php and mysql - php

I have some blogposts and I want to create a link of archives.
The link will go to a page that will only return results from a particular quarter, how do I do this with php and mysql?
So I have a "date" field in a table and only want to return results from this quarter - e.g. the link to Quarter one will only return results from 1 Jan - 30th March.
I could do this with a set of static queries and dates but I would like to do it a more programmatic way.

Edit: You're talking about quarters of a year, not a quarter (1/4) of the result set.
Step 1: This depends on how your year is split up. (fiscal/etc)
Step 2: Use a WHERE clause that filters for the right months. Some variation of Date_Format().
SELECT * FROM <table>
WHERE Date_Format(date_stamp,'%Y-%m') IN ('2010-10','2010-11','2010-12')
Of course, you'll want to do some PHP to determine the months you need in place of the hard-coded month strings. But, that should get you where you need to be for a quarterly report. The reason I'm not saying use QUARTER(date) (which returns 1 - 4) is because sometimes your quarter needs to be customized, and the more generic, home-rolled mechanism is far more customizable. (And, you haven't said what quarter system is needed.)
Note: You can also use this sort of technique to do a grouping if you want a summary (total/avg/etc) on some field that's in the group as well.

This is the code I used:
$quarter = $_REQUEST['quarter'];
$quarter_conf = array(1=>"('2011-01','2011-02','2011-03')", 2=>"('2011-04','2011-05','2011-06')",3=>"('2011-07','2011-08','2011-09')", 4=>"('2011-10','2011-11','2011-12')");
$sql = "SELECT * FROM table where Date_Format(`date`,'%Y-%m') IN ".$quarter_conf[$quarter]." ORDER BY `date` DESC";

Related

Get all rows from a specific month and year

I have a PHP scirpt that is always querying all the data from a database table and it's getting pretty slow. I really just need the data of a specific month and year.
Is there a simple way to get only those entries? For example, everything from February 2013?
The column that stores the dates in my table is of type datetime, if that applies to the solution.
You can add that condition in the WHERE clause of your select statement. I would recommend using BETWEEN operand for two dates:
SELECT myColumns
FROM myTable
WHERE dateColumn BETWEEN '2013-02-01' AND '2013-02-28';
If you mean to say you want everything beginning with February 2013, you can do so using the greater than or equal to operator:
SELECT myColumns
FROM myTable
WHERE dateColumn >= '2013-02-01';
EDIT
While the above are my preferred methods, I would like to add for completeness that MySQL also offers functions for grabbing specific parts of a date. If you wanted to create a paramaterized query where you could pass in the month and year as integers (instead of a start and end date) you could adjust your query like this:
SELECT myColumns
FROM myTable
WHERE MONTH(dateColumn) = 2 AND YEAR(dateColumn) = 2013;
Here is a whole bunch of helpful date and time functions.
You should index the datetime field for added efficiency and then use Between syntax in your sql. This will allow the mysql engine to remove all records that you are not interested in from the returned data set.

Proper MYSQL syntax for timestamp comparison and distinct results with certain exclusions

Sorry for asking, but I've never had to do such a complex MYSQL query before and I don't actually know what to google search in order to get the answer.
I have a poorly crafted database with a table of appointments of pregnant women that includes the day they came and the number of weeks pregnant they were at that time. I'm trying to select each one that should be 30 weeks right now but that doesn't already have a separate entry after 25 weeks pregnancy. I use the phone number to uniquely identify each person.
Since I really don't know how to formulate this query, this is the best I've come up with.
SELECT * FROM patientlist WHERE
UNIX_TIMESTAMP() - (UNIX_TIMESTAMP(`date`) - `weekspreg`*604800) > 29*604800
AND
UNIX_TIMESTAMP() - (UNIX_TIMESTAMP(`date`)- `weekspreg`*604800) <= 30*604800
AND
/* a subquery that keeps out results where the phone number would show up elsewhere in the table for a woman with more than 25 weeks of pregnancy. */
There has to be a better solution than separately querying each of the results from the date range by phone number to see if the weekspreg is more than 25.
Thank you in advance for any help or direction.
Your entire WHERE is incorrect. A query can only have ONE where clause. You join multiple conditions with and and or, not and where:
WHERE foo AND bar // correct
WHERE foo AND WHERE bar // syntax error
Check out the MySQL Date and Time Functions. For example, I'm not entirely certain what that last WHERE clause is trying to do, but I believe the first portion could be rewritten as something like:
SELECT *
FROM patientlist
WHERE `date` - interval `weekspreg` week
between now() - interval 29 week
and now() - interval 30 week

PHP and MySQL - display contnet of column between certain numerical values

I'm new to MySQL and PHP but was wondering if someone could help me with a little project I'm doing for my boss.
I have a SQL database (MyDB) and a table in there (mytable) with two columns - the first column (index) is an auto-incrementing integer from 1-10, the second column (date) has different dates and timestamps in the format of Year-month-day time 2013-04-12 1326
I'm trying to create a simple PHP page that first gets the current date (easy enough) then looks at the table and shows the number of rows that fall within yesterday's date. For example, if I have 3 rows with 2013-04-11 XXXX and 2 rows with 2013-04-12 XXXX (and today is the 12th April 2013) the page will display 3. (The time is not important but we can't remove it from the table as it's auto created by one of the other staff's programs and he refuses to change it).
So far I've got my php page, done a connection to the DB and defined two variables:
$startdate = date('Y'."-".'n'."-".'d'." "."0000");
$enddate = date('Y'."-".'n'."-".'d'." "."2359");
As the timestamp doesn't matter I've gone for the min/max possible on the variables. I realise this will only give the current date, trying to work out how to get it to display the previous day as the date in the variable.
Now I'm trying to create a sql query that will count the number of rows where the date field falls within the startdate and enddate variables (-1 day) but not too sure where to start or how this would look. I then need to output this as a variable in PHP so I can echo it later in the page.
Anyone able to point me in the right direction? Hope any of this makes sense.
You could write a query with no params to do this (if its always just yesterday).
SELECT * FROM <table>
WHERE DATE_FORMAT(<date column>,'%j-%Y') = DATE_FORMAT(DATE_SUB(now(),INTERVAL 1 DAY), '%j-%Y');
Date functions in the where clause might not be super awesome performance wise

Search for age in php

I am trying to build up a search function, which gets the results by an age range. The database containts the birthday of an user (e.g. 1980-09-11 00:00:00). Now I am trying to search for users e.g. by using $agefrom = 15; and $ageto = 18;.. But I do not now how the php code and the db statement should look like..
I want to make the most stuff in php and then only do a sql query like (birth < birth_to AND birth > birth_from)..
Thank you for your help!
The simplest query, which won't work with total accuracy would be
SELECT ...
FROM ...
WHERE YEAR(birthday) BETWEEN (YEAR(now()) - 18, YEAR(now()) - 15)
This will fail if a person's birthday has not yet occured in a particular year (e.g. it's May 1st, and their b-day is June 15th). Handling that case will require a bit more date math to check for "year is right but day/month is wrong".
I would think it's easiest to construct the dates you need as 15 and 18 years ago (in PHP), then place those in the query with a BETWEEN statement. Round to midnight or you'll get bad edge cases.

How to sort data depending on what day it was posted?

How do you sort data which was stored in a mysql database depending on the days of the week in which the data was submited ??
I basically want to create a diary which outputs information in each day of the week depending on what day it was posted by dates so,
Mon - Data in order of date
Tue -
Wed - e.t.c
Any code examples and information will be great, thanks.
You can do a
SELECT DAYOFWEEK(datehere) as dayofweek, datehere FROM something ORDER BY dayofweek, datehere;
You can use the DAYOFWEEK function to extract the day, and then sort on it just like any other data.
What kinf of data type is the column where you store the date submission?
It seems like you're asking for a basic SELECT statement?
SELECT some_column, another_colum FROM your_table ORDER BY your_date_column DESC
This assumes you actually have a column that logs the insertion timestamp.
If this answer is obnoxiously simplistic, please forgive me...and give us more details :)
Regards.
If your data is stored as a DATE or DATETIME field, use the DAYOFWEEK or DATE_FORMAT functions to turn it into day name for output, but continue to order by the DATE field
SELECT DATE_FORMAT(my_date_column, '%W') AS dayofweek
FROM my_table
ORDER BY my_date_column
Well, the sorting bit is easy, just sort on the column that represents the post's date. The grouping in days is something you can do in your code, since you need to check the date there anyway (for post-processing the actual output).
To put it this way, you can do a subselect to get the specific day of the week, but in your code you would have to check the day again to group posts per day. In that case it's better (and cleaner, since you're separating business logic from data) to do this in your code, something like this:
select all posts (within date range)
make an associative array, with the
days as keys, and posts (in new
arrays) as values
loop through the
days and then posts to output the
posts per day
SELECT *
FROM diary_entries
ORDER BY FIELD(DAYOFWEEK(created), '2, 3, 4, 5, 6, 7, 1'), created
DAYOFWEEK grabs day of the week number (1 = Sunday).
FIELD makes Monday first day of the week.
After sorting by day of week, then sorted by date created.

Categories