开发者

How to get a mysql datetime field as a datetime in php?

开发者 https://www.devze.com 2023-02-09 00:17 出处:网络
I am new to PHP and MYSQL so this should be a pretty basic question. I am querying a mysql database and getting thre开发者_运维问答e fields into an array. One of the fields type is datetime, but with

I am new to PHP and MYSQL so this should be a pretty basic question.

I am querying a mysql database and getting thre开发者_运维问答e fields into an array. One of the fields type is datetime, but with my current query, it is being captured as a string.

This is my code:

$myquery = mysql_query ("SELECT id,text,when FROM messages ORDER BY cuando DESC");
 $nrows = mysql_num_rows ($myquery);
 for ($i = 0; $i < $nrows; $i++) {
 $row = mysql_fetch_assoc ($myquery);
 $when = $row["when"];

I've been googling and I think i have to use the AS operator in my query, but I dont' know how. How can I do this? If possible, just by changing the query...

Thanks!


  1. in PHP: $when = strtotime($row["when"]);
  2. in mySQL: SELECT id, text, UNIX_TIMESTAMP( when ) AS when FROM...


If you want a unix timestamp, you can either do it in your query or in php.

In your query:

$myquery = mysql_query ("SELECT id,text,UNIX_TIMESTAMP(when) FROM messages ORDER BY when DESC");

in PHP:

$when = strtotime($row['when']);

Edit: WHEN being a reserved MySQL keyword, this query will give an error. Use something else for your date field.

0

精彩评论

暂无评论...
验证码 换一张
取 消