如何在php中将mysql datetime字段作为日期时间?

时间:2022-09-25 15:47:55

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

我是PHP和MYSQL的新手,所以这应该是一个非常基本的问题。

I am querying a mysql database and getting three fields into an array. One of the fields type is datetime, but with my current query, it is being captured as a string.

我正在查询一个mysql数据库并将三个字段放入一个数组中。其中一个字段类型是datetime,但是使用我当前的查询,它将被捕获为字符串。

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...

我一直在谷歌搜索,我想我必须在我的查询中使用AS运算符,但我不知道如何。我怎样才能做到这一点?如果可能,只需更改查询...

Thanks!

2 个解决方案

#1


3  

  1. in PHP: $when = strtotime($row["when"]);
  2. 在PHP中:$ when = strtotime($ row [“when”]);

  3. in mySQL: SELECT id, text, UNIX_TIMESTAMP( when ) AS when FROM...
  4. 在mySQL中:SELECT id,text,UNIX_TIMESTAMP(when)当FROM时的AS ...

#2


0  

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

如果你想要一个unix时间戳,你可以在你的查询或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.

编辑:当作为保留的MySQL关键字时,此查询将给出错误。在日期字段中使用其他内容。

#1


3  

  1. in PHP: $when = strtotime($row["when"]);
  2. 在PHP中:$ when = strtotime($ row [“when”]);

  3. in mySQL: SELECT id, text, UNIX_TIMESTAMP( when ) AS when FROM...
  4. 在mySQL中:SELECT id,text,UNIX_TIMESTAMP(when)当FROM时的AS ...

#2


0  

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

如果你想要一个unix时间戳,你可以在你的查询或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.

编辑:当作为保留的MySQL关键字时,此查询将给出错误。在日期字段中使用其他内容。