Getting mySQL date_format to display in PHP - php

This could sound like a very simple question to many of you, but I seem to be having trouble getting a basic date_format to work with my mySQL statement and then to be displayed using php. Here is the code that I currently have:
$result = mysql_query("SELECT *, DATE_FORMAT('timestamp', '%W %D %M %Y') as date FROM articleDB WHERE userID='".$_SESSION["**"]."' ORDER BY timestamp DESC LIMIT 8");
Then trying to display it using:
echo ' Posted: '.$row['timestamp'].'';
All I want is to format the date from a PHP myAdmin timestamp to the format I want.
Cheers

Use backticks ( `` ) or nothing at all instead of single-quotes ('`) around your field in your query:
$result = mysql_query("SELECT *, DATE_FORMAT(`timestamp`, '%W %D %M %Y') as date FROM articleDB WHERE userID='".$_SESSION["**"]."' ORDER BY timestamp DESC LIMIT 8");
Backticks ( `` ) creates a reference to a table member, single-quotes creates a string ('). You were basically trying toDATE_FORMATthe string'timestamp'` instead of the field.
Also, since you are using as to create a field alias, you want to refer to that field using the alias when outputting:
echo ' Posted: '.$row['date'];

you need to display the "date" column that you calculate/format in the select statement, the timestamp column contains the unformatted original date value.
echo ' Posted: '.$row['date'];

since in your SQL query you define the date formatting as date you access it by $row['date'].

Related

convert Unix Time stamp and sort data in mysql query

I am trying to query a small database by date, my date table data is stored in time 2014-02-04 . how can I convert that and check it against todays date.
This is what I have but I am getting a few errors
$q = 'SELECT count(*) as count FROM SHOW WHERE date('Y-m-d', strtotime
('SHOW_DATE') ='.$db->qstr(date()).' AND CONTACT='.$db->qstr($name);
if(!$rs = $db->execute($q)){
force_page('core', 'error&error_msg=MySQL Error: '.$db->ErrorMsg().'&menu=1');
exit;
} else {
$today_count = $rs->fields['count'];
$smarty->assign('today_count',$today_count);
}
Thanks a lot.
You can convert show_date to a date format using FROM_UNIXTIME function. And then compare the date part of it with your input date value.
Example:
SELECT count(*) as count FROM `SHOW`
WHERE date( from_unixtime( `SHOW_DATE` ) ) = ? AND CONTACT=?
Use prepared statement to bind input values to the place holders.
To find a row containing a DATE matching the current date, use CURDATE():
SELECT column FROM table WHERE col_date = CURDATE()

php mysql comparing dates for equality

I am using php to access fields from 2 tables.
This part works just fine
$sql=mysql_query('SELECT * FROM user_weeks WHERE user_id = '.$_SESSION["user_id"].' ORDER BY date DESC') or die(mysql_error());
I get the date just fine by doing this
$infodate=$info["date"];
echo $infodate;
However I'm trying to take that date and compare it to one in a different table as such
$sql2=mysql_query('SELECT * FROM weekly_ROI WHERE date = '.$infodate.' ') or die(mysql_error());
however, that gives me no results. I'm a noob so sorry if this code is so "2000 and late"
Assuming both date fields are of type date, you need to wrap the name date in backticks, since date is a reserved word and you need to wrap your date in quotes.
$sql2=mysql_query('SELECT * FROM weekly_ROI WHERE `date` = "'.$infodate. '"') or die(mysql_error());
Also, mysql_* functions are deprecated. You need to look into using PDO or mysqli to query your database.
date is reserved word use to wrap inside the backtick `date
$sql2=mysql_query('SELECT * FROM weekly_ROI WHERE `date` = "'.$infodate.'" ') or die(mysql_error());
Presumably you're using a standard yyyy-mm-dd type date string in your query, which means you're lacking quotes around the date value:
$sql2=mysql_query('SELECT * FROM weekly_ROI WHERE date = '.$infodate.' ')
^--here ^-- here
Your query will look like
... WHERE date = 2013-12-18
and be evaluated as a simple mathematical subtraction:
... WHERE date = 1983
You need quotes:
.... date = "' . $infodate . '"');
^-- ^--

PHP Matching the output of 2 codes

I need to match the result format of 2 code:
I need to get the output/format of this:
$event_day = $year.'-'.$month.'-'.$list_day; // $event_day
match this:
DATE_FORMAT(date,'%Y-%m-%d')
Full code:
$query = "
SELECT title, DATE_FORMAT(date,'%Y-%m-%d') AS date
FROM table
WHERE user_id = '$session_user_id'
AND date BETWEEN '$year-$month-1' AND '" . date("Y-m-t", strtotime("$year-$month-1")) . "'
AND active = 1";
My problem is that $event_day is only displaying events for: October, November and December.
I had a similar problem with this code below:
$query = "
SELECT title, DATE_FORMAT(date,'%Y-%m-%d') AS date
FROM table
WHERE user_id = '$session_user_id'
AND date LIKE '$year-$month%'
AND active = 1";
and it was fixed with this code:
$query = "
SELECT title, DATE_FORMAT(date,'%Y-%m-%d') AS date
FROM table
WHERE user_id = '$session_user_id'
AND date BETWEEN '$year-$month-1' AND '" . date("Y-m-t", strtotime("$year-$month-1")) . "'
AND active = 1";
Anyone know how I could sort this out?
If you are simply trying to match dates in a SQL query, which is what you look like you're after, you can just pass the date as a string with a # on each end. This will tell SQL to parse the string as a date and the format you give it in is not really important. The exception to this is it can get confused between US/EU date formats like dd/mm/yyyy vs mm/dd/yyyy.
$query = "SELECT title, DATE_FORMAT(myDate,'%Y-%m-%d') AS formattedDate
FROM table
WHERE user_id = '$session_user_id'
AND (myDate BETWEEN #$year-$month-1# AND #$year-$month-1#)
AND active = 1";
This format should work but your query is select records that fall between the same date so you'll only get records that are actually on that date. You might as well just use WHERE date = #$year-$month-1#
edit: this assumes your date field datatype is correctly set up in the database as a date/time.
edit2: "date" is often a reserved word in databases and shouldn't really be used for field names and variables. See edited code above.
In addition I would suggest using php to format the date using the date() function rather than format it in the query. This allows more flexibility to actually use the date in your script.

Format date from mysql query with multiple tables

I have an sql query that I use to display the news section of my website.
I would really love for the dates to be presented as "2nd January, 2012" however as I am selecting all fields from 5 tables I don't know where to put my formatting requirements (I am not selecting individual fields).
My query is below:
$query_newsheadlines = "
SELECT *
FROM
NewsArticles,
NewsArticleCategories,
NewsArticlePhotos,
NewsCategories,
NewsPhotos
WHERE
NewsArticles.id = NewsArticleCategories.newsArticleID
AND NewsArticles.id = NewsArticlePhotos.newsArticleID
AND NewsArticlePhotos.newsPhotoID = NewsPhotos.id
AND NewsArticleCategories.newsCategoryID = NewsCategories.id
AND NewsCategories.SectionID = 201
ORDER BY NewsArticles.publishDate DESC";
Any ideas would be appreciated :)
update the column my date is located in is NewsArticles.publishDate
you need to specify what column do you want to be formatted (just don't be lazy on specifying the column). Use DATE_FORMAT
SELECT DATE_FORMAT(CURDATE(),'%D %M, %Y')
SQLFiddle Demo
Other Source(s)
DATE_FORMAT()

Selecting from a MySQL DB based on parts of a timestamp

Is there a way to select rows from a DB where the timestamp is in a certain year? I don't have a specific timestamp, just a range (ex. all timestamps within the year 2009). Is there a way to do this? How else might I go about doing something like this? Thanks for your help!
-iMaster
Use:
WHERE timestamp_col BETWEEN STR_TO_DATE('2009-01-01', '%Y-%m-%d')
AND STR_TO_DATE('2009-12-31', '%Y-%m-%d')
Any functions performed on a column mean that an index, if one exists for that column, can not be used.
I used the STR_TO_DATE function to ensure that whatever date provided as a string could be interpreted by MySQL as a TIMESTAMP.
Reference:
STR_TO_DATE
As simple as:
SELECT * FROM table WHERE YEAR(timestamp) = '1999'
Use FROM_UNIXTIME similar to this:
SELECT
FROM_UNIXTIME(my_timestamp, '%Y') AS year
FROM
table_name
WHERE
FROM_UNIXTIME(my_timestamp, '%Y') = 2009;
Where 'my_timestamp' is the name of your timestamp column.
Alternatively you can also convert it to a DATETIME
If you convert it to datetime you can do it by using the mysql DATE_FORMAT function which allows you to take a DATETIME and format it as a date. Then group by that column.
private function _formatDate() {
if ($this->_granularity == 'month') {
return '%y/%M';
}elseif($this->_granularity == 'day') {
return '%y/%M/%d';
}
}
public function getmyquery() {
$query = "
SELECT count( * ) as visits, DATE_FORMAT( `myOriginalDateField` , '".$this->_formatDate()."' ) AS mydate
FROM `mys`
WHERE id = ".$this->_Id."
GROUP BY mydate
ORDER BY mydate ASC
";
return $query
}
An important addition to the excellent suggestions already given here: if you plan on executing this query as a part of rendering your pages (as opposed to running this as a one-off report), you should really consider performance. Indexes won't help you much if you're post-processing the column value with a function before comparing it to something.
In that case, I would consider creating a separate database column that contains JUST the year, or just the month, etc.

Categories