Get specific part of a row from MySQL - php

I am doing upcoming event which takes data from MySQL of another script (in this case, another Joomla extension)
Thanks to Alex Mihai, I know how to show upcoming event:
SELECT * FROM EventTable
WHERE Date > CURDATE()
ORDER BY Date
LIMIT 1;
Now I need to show a date of that event in a specific way. I have date of event in a row in this format (numbers as example): 2012-12-30
Is it possible to select only the middle characters (month number) from this row and make something like this:
if 12 = December, if 01 = January and etc. (month names are just example)
For a clear image I am trying to make an upcoming event with this data:
3 first letters of the month in native language, day of the month, event title (event title already works)

use DATE_FORMAT
SELECT DATE_FORMAT(columnName, '%M %d, %Y') eventDate
FROM tableName
by the way, this outputs January 01, 2013
for more formats, click the link below
Format Date Fields Using MySQL DATE_FORMAT()

With PHP you can also do it:
$date = strtotime($row['Date']);
echo date('D j', $date);
More on date() and formatting options: http://php.net/manual/en/function.date.php

Related

MySQL Delete Row That Is Older Than The Current Date

I am trying to delete events in my database that have a start date older than the current day.
I've used the NOW statement and it deleted all of the content within my table.
The database is updated daily with events and I want to delete the events that have passed.
Here is a sample of my sql statement:
mysql_query("DELETE FROM Detroit WHERE Detroit.startDate < CURDATE()");
startDate is the name of the column in the db where all of the date information is stored.
The dates appear as Fri, 25 Apr 2014 19:00:00. When I use the CURDATE or NOW date options within my statement, the whole table is deleted. How do I delete the rows with the dates older than the current date?
I suspect that your startDate column is not a datetime field, but it's a varchar instead.
This query should work:
DELETE FROM Detroit
WHERE STR_TO_DATE(startDate, '%a, %e %b %Y') < CURDATE()
Or you could try to substitute %e with %d. However, it is always a better idea to use a DATETIME column and not a VARCHAR column to store date and times, so you should create a new column startDatedt and update your table this way:
UPDATE Detroit
SET startDatedt = STR_TO_DATE(startDate, '%a, %e %b %Y %H:%i:%S')
and then you could just use date and time functions to delete the rows that you need:
DELETE FROM Detroit WHERE startDatedt < CURDATE()
Please have a look here to see how to compose a date format string.
If you're working with the UNIX Timestamp(Seconds after the 1st january 1970, this format is always in UTC), you can use this code:
mysql_query("DELETE FROM Detroit WHERE Detroit.startDate < ".time());
Let me know if you're using another format and I make another code snippet.
Try this code and let me know its result please:
mysql_query("DELETE FROM Detroit WHERE DATEDIFF(CURDATE(),startDate) > 0");

Fixing old MySQL date field mistake

I've have a date field in my table that stores dates from a form in a Weekday, Day Month, Year string.
Example: Wednesday, 02, November 2010
the field is also a varchar.
can I loop through the entire table with a php script to convert the dates to a mysql date format or perform this with an SQL query?
I'm not sure that I can preform some certain statistical reports that involve picking out certain dates and date ranges in the format I have now. What are my options?
No need to get PHP involved. It can be done directly in MySQL:
ALTER TABLE yourtable ADD fixeddate date;
UPDATE yourtable SET fixeddate=STR_TO_DATE(bad_date_field, '%W, %d, %M %Y');
relevant docs here: http://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html#function_str-to-date
PHP has a built in class called DateTime. Here is a snippet of code that should get you started.
$date = DateTime::createFromFormat('l, d, F Y', 'Wednesday, 02, November 2010');
echo $date->format('Y-m-d');
You can find more info about this class at http://au.php.net/manual/en/book.datetime.php

Sorting through a Database query for all rows created in the same day Unix Timestamp in PHP

I am developing a PHP application which will handling many company articles.
Now I am creating a page which should order articles BY DATE ie all articles created in a certain day are shown with the appropriate heading and so on for all the articles.
I have used Unix timestamps to save the dates in the MySql db but I cant find code which only sorts dates by days. Can I please get some assistance.
Thanx
You can use mktime() to get the timestamps you would want to use to bin the entries:
http://us.php.net/manual/en/function.mktime.php
$timestamp_for_my_birthday = mktime(0,0,0,10,16,1984);
$timestamp_for_the_next_day = mktime(0,0,0,10,17,1984);
if($time > $timestamp_for_my_birthday && $time < $timestamp_for_the_next_day){
// Time is on my birthday
}
To make this into a MySQL query:
$SQL = "SELECT * FROM dates WHERE date > $timestamp_for_my_birthday AND date < $timestamp_for_the_next_day;";
To order by date I think it would go something like:
SELECT * FROM dates ORDER BY FROM_UNIXTIME(time, '%M %d %Y');
Can you do a
SELECT DATE(FROM_UNIXTIME(my_field_name)) FROM table_x ORDER BY my_field_name
You can order by the timestamp column, but if you want a string representation of which day the record belongs to, you can get any part of the date with the FROM_UNIXTIME(timestamp, 'format') function.
select FROM_UNIXTIME(timestampColumn, '%Y %m %d')
The format values in the second parameter can be adjusted based on the table here:
http://dev.mysql.com/doc/refman/5.1/en/date-and-time-functions.html#function_date-format

getdate() in mysql

I am creating a system which updates the user activity when something is done.
I have a variable $userhistory= 'User edited '.$info.' on July 14 2010 or (07-14-2010);
I want to know how can i get the date automatically. for sql query i am using NOW(), but in a variable like $userhistory how do i get the date and it want it only in either of these forms. not along with the time.
Also, I am updating the column userhistory in the database, which is a text field. Is this the correct way to do it? How can i save only 5 or 10 of the last few updates?
If you are using NOW() when you update or write an entry to the database, the column storing the date (userhistory?) should be of DATETIME type.
Then you'd you'd run your SQL as normal :
SELECT field1, field2, UNIX_TIMESTAMP(userhistory) FROM table;
Then in PHP, use date() on the database result to format it accordingly:
// July 14 2010
date('F j Y', $row['userhistory']);
// 07-14-2010
date('m-d-Y', $row['userhistory']); ,
You can do it without PHP as well.
SELECT
DATE_FORMAT(date_column, '%M %d %Y') AS 'Formatted',
DATE_FORMAT(date_column, '%m-%d-%Y') AS 'Formatted2'
FROM
table;

Archive Builder PHP

Before i start id like to say ive posted this question as more of a discussion rather than Problem Question.
In my Database i have news posts lets say with 3 columns (Id, title, date). Wher Id and title are self Explanitory the date is stored in mktime() values, in other words the number of seconds passed since 1 January 1970.
Now what i want to do is build an archive link that will display as such
July 2009
June 2009
March 2009
Feburary 2009
December 2008
Note the months on which there were no posts are not displayed.
Now as an initial thought i was thinking
Start with the last day of the current Month
And get the Value of the First day of the current Month
Do a MySQL COUNT Query/mysql_num_rows for posts that were date >= First_Day_Seconds AND date <= Last_Day_Seconds
Display or put the values in an Array
Do another Query to Check if Any more values are found WHERE date < First_Day_Seconds (break if no rows were found)
Now the above is just something on the top of my head. But if you got any ideas to speed this process up please share.
Will say in advance, date needs to be in mktime format
I would suggest using a database "native" time format, but it works with UNIX timestamps as well.
You can simply do:
SELECT DISTINCT FROM_UNIXTIME(date, '%M %Y') FROM posts;
Optionally with a WHERE clause limiting the dates to past or future dates. Possibly an ORDER clause thrown in for good measure. That should be pretty much all that's needed, let the database do as much work as possible.
If you need more formatting options, select the dates with "%Y-%m" instead and format them in PHP:
date($myCustomFormat, strtotime("$date-01"));
You can use this query to get years
"SELECT *,content_id,COUNT(content_id) AS itemCount FROM content_mast GROUP BY DATE_FORMAT(date_upload,'%Y') DESC";
now use can use this query to get month of that year
$tday = date("Y", $datetime);
$s1="select * from content_mast where DATE_FORMAT(date_upload,'%Y')=$tday";

Categories