Building a text string from date details in MySQL - php

I've hunted around and found plenty of ways to convert a string to a date, but I can't seem to find one for the reverse... so here we go.
I'm trying to build a text string for a query, specifically running through WordPress on MySQL, for the BAW Post Count plugin data. That plugin uses a meta-key which always begins the same (count-views) and is followed by 'day', 'month' and so on, then the date part.
What I want to do is specify which meta-key I'm looking for by building a text string based on the current date:
"_count-views_month-" then the 4-figure year and two-figure month.
For example, this month is October 2013, so it would come out as "_count-views_month-201310"
The problem is that I can't seem to find a way to get the year and month as text, for use in a php script.
I've tried using year(now()),year(date(now())), cast, concat and a variety of other things but none seem to work. I know it must be incredibly easy and I'm just complicating matters or overlooking something obvious, but I can't see what!
So, the question is how I can do that as a "$variable=" statement, please.
Thanks!

You over-thought it:
echo date("Ym"); // outputs "201310"
Full example:
echo '_count-views_month-' . date("Ym");
Or:
printf("_count-views_month-%s", date("Ym"));
Or, in SQL:
SELECT CONCAT("_count-views_month-", DATE_FORMAT(CURRENT_DATE, "%Y%m"))

Related

Extract an 8 character integer string from an ical file

This code to get all sequences of 8 integers works fine:
preg_match_all('/[0-9]{8}/', $string, $match);
However I am only interested if the match starts with 20.
I know I have to add ^20 somewhere but I have tried many times with no success. I have looked at many regex tutorials but none of them seems to explain how to do 2 separate searches.
I am actually trying to parse ICAL files to extract the dates. If the 8 digit integer starts with 20 it almost certainly is a date.
For example: DTSTART:20150112T120000Z
How about this solution:
/(20)\d{6}/
This will probably find what you are looking for:
(?=20)(\d{8})
It does a positive lookahead to capture a group if it starts with 20 along with a 8 digit number.
The answer highly depends on what you want to achieve. Do you want to extract all and any dates from an icalendar file. If so, you might be missing birthday dates as their year are most likely to be starting with 19xx.
Also matching any dates will yield most likely many undesired dates like UNTIL, TRIGGER, DTEND, ...
Assuming from your example you want to extract events start dates, you could try:
DTSTART[a-zA-Z._%+-/=;]*:(\d){8}[T]?[\d]{6}
To be kept in mind: following DTSTART can be a timezone definition like TZID=America/New_York and/or the type definition DATE or DATE-TIME (see RFC5545 DATE-TIME

Advanced statistics in PHP and MySQL

I have a slight problem. I have a dataset, which contains values measured by a weather station, which I want to analyze further using MySQL database and PHP.
Basically, the first column of the db contains the date and the other columns temperature, humidity, pressure etc.
Now, the problem is, that for the calculation of the mean, st.dev., max, min etc. it is quite simple. However there are no build-in commands for other parameters which I need, such as kurtosis etc.
What I need is for example to calculate the skewness, mean, stdev etc. for the individual months, then days etc.
For the build-in functions it is easy, for example finding some of the parameters for the individual months would be:
SELECT AVG(Temp), STD(Temp), MAX(Temp)
FROM database
GROUP BY YEAR(Date), MONTH(Date)
Obviously I cannot use this for the more advanced parameters. I thought about ways of achieving this and I could only think of one solution. I manually wrote a function, which processes the values and calculates the things such as kurtosis using the particular formulae. But, what that means is that I would need to create arrays of data for each month, day, etc. depending on what I am currently calculating. So for example, i would first need to take the data and split it into arrays lets say Jan11, Feb11, Mar11...... and each array would contain the data for that month. Then I would apply the function on those arrays and create new variables with the result (lets say kurtosis_jan11, kurtosis_feb11 etc.)
Now to my question. I need help with the splitting of data. The problem is that I dont know in advance which month the data starts and which it ends, so I cannot set fixed variables for this. The program first has to check the first month and then create new array for each month, day etc. until it reaches the last record. And for each it would create the array.
That of course would be maybe one solution but if anyone has any other ideas about how to go around this problem I would very much appreciate your help.
You can do more complex queries to achieve this. Here are some examples http://users.drew.edu/skass/sql/ , including Skew
SELECT AVG(Temp), STD(Temp), MAX(Temp)
FROM database
GROUP BY YEAR(Date), MONTH(Date)
having date between date_from and date_to
I think you want a group of data in between a data range.

Mysql query to show results from between two columns

Hi i have a mysql database, in which i have two columns Year_from & Year_two.
what i am trying to do is find a way where i can show the dates that are missing as buttons, for example if year from is 2006 and year to is 2008, i of course want to show 2006, 2007 and 2008. is this possible, as there isn't the value of 2007 in the database.
I haven't worked on any code yet as i am not sure if this is possible, or how i would achieve it.
Any ideas would be appreciated.
Thanks
Use range($year_from, $year_to) to generate a list of all years. Compare that array with the one you got from the database using array_diff() and bold the missing ones.
This needs to be done in code.
Basically, you'll read a bunch of records from the database, iterate through an array of years you'd like to show and check (every iteration) if there is a matching record present in the result set.

Best way to search a comma separated mysql field

I have been given the task to combine 2 mysql fields into one and then make it so that the new field can be searched. The 2 fields I had to combine in my database where previous year registered and current years registered. The format both these fields are in are dd/mm/yyyy. I have combined these fields into a field called Years Registered whih is still in the same format dd/mm/yyyy but has the years registered seperated by a comma(,). I am wondering how I would go about performing a couple different kinds of querys on this column. The mysql queries I have to perform are: Show All() , Show All between dates: mm/yyyy and mm/yyyy , Before: mm/yyyy , After: mm/yyyy
Any help would be greatly appreciated.
Thanks for your time.
I don't like it but if you need you can use the next solution:
extract date using start_date = STR_TO_DATE(SUBSTRING(your_new_field, 1, 10))
and end_date=STR_TO_DATE(SUBSTRING(your_new_field, 12, 10))
Do not do this!
I do not know how it is exactly possible (some SQL Stringoperations and Datefunctions in a storedprocedurem i presume), but it will surely kill performance of your database.
use a relation for this.
This is:
way faster
more expandable (eg. for three dates..)
easier to code
much better understandable
more portable to other databases
If you have problems with existing platforms you have to support, use a code base where both alternatives are supported. This is still easier and better to maintain than to use a comma-separated list
Your database would be breaking 'First Normalized Form (1NF)' and would be highly ineffecient.
In order to search for a selected date, you would either have to query all rows in the table, or use LIKE which is also very sluggish.
Whoever is asking you to do this should read this article on database normalization.
What is wrong with using two DATE, or DATETIME fields and the formatting them outside of MySQL?

DD-MM-YYYY date format and MySQL

I have a MySQL table:
dateStarted varchar(45)
dateEnded varchar(45)
Example:
alt text http://img8.imageshack.us/img8/765/dated.jpg
There is varchar (I don't know why the previous software engineer used this).
Can I search between two dates in MySQL with the varchar type?
Nope. You have to change the format to a proper one.
The previous software engineer used this because of ignorance. You have to correct his mistake.
Don't be afraid of some extra work. Actually it's part of every programmer's job. There is no code in the whole world, which is perfect forever. Constant code improving is called refactoring and take a big part of every software engineer's worktime.
SELECT
*
FROM test1
WHERE STR_TO_DATE(:date, '%d-%m-%Y') BETWEEN
STR_TO_DATE(dateStart,'%d-%m-%Y') AND
STR_TO_DATE(dateEnd,'%d-%m-%Y')
Just tried this on your dataset, and it works AFAICT.
But you should of course heed the advice given by the others here, and try to fix your predecessor's mistakes, if at all possible within time-constraints. This will become an issue at some point, due to the amount of casting going on.
You will need to determine the format that the two fields are in. Are they seconds from UNIX epoch? Are they YYYYMMDD format? Once you've done that, it would be fairly easy to convert it to a date and compare them.

Categories