【问题标题】:Use datetime data from SQL query to populate "input type=time" field使用 SQL 查询中的日期时间数据填充“输入类型=时间”字段
【发布时间】:2016-04-21 18:11:35
【问题描述】:

我正在尝试使用 PHP 进行 SQL 查询,以填充表单中的各个字段,以便站点管理员可以对其进行编辑。这两个字段是日期和时间。

我使用两种输入类型“日期”和“时间”。日期字段填充完美。时间字段将变为空白。两者的数据都来自同一个 SQL 查询。我希望它们都以每个字段的预期格式显示。 (我正在为此使用 Chrome,因为我知道并非所有浏览器都支持字段类型)。

//Queries
        $pull_game = "select datetime, city, opponents.opponent_id, game_type, tourn_name, time, home_score, vis_score, day_of_week, month, day, year, parks.park_id, park, win, loss, tie, result from games, opponents, parks, tournaments where opponents.opponent_id = games.opponent_id and parks.park_id = games.park_id and tournaments.tourn_id = games.tourn_id and game_id= ".$_POST['game_id'] . ";";
        $game_stats = mysqli_query($con,$pull_game) or die("ERROR: $pull_game. ".mysqli_error());
        $game = mysqli_fetch_array($game_stats);

//Display data
        <input type='date' name='date' value=<?= $game['datetime']?>>
        <input type='time' name='time' value=<?= $game['datetime']?>>

我尝试删除日期字段以查看时间字段是否有效,但它仍然是空白的。我没有运气研究这个 - 我发现的大部分内容都是用日期时间数据更新数据库。我正在寻找相反的(有点)。

任何帮助将不胜感激。

【问题讨论】:

  • 您要在其中填充完整的日期/时间字段? yyyy-mm-dd hh:mm:ss 不是有效的“时间”值,因此如果该字段为空白,请不要感到惊讶。
  • 也缺少引号。

标签: php mysql datetime


【解决方案1】:
//Queries
        $pull_game = "select date(datetime) as d, time(datetime) as t, city, ..."

//Display data
        <input type='date' name='date' value=<?= $game['d']?>>
        <input type='time' name='time' value=<?= $game['t']?>>

应该可以解决问题。 HTML5 输入的有效日期和时间格式在https://www.w3.org/TR/html5/infrastructure.html#dates-and-times 中进行了描述 - 本质上,“日期”是 YYYY-MM-DD,“时间”输入是 HH:MM:SS。方便的是,这正是 MySQL 的 date() 和 time() 函数的输出(cp.http://dev.mysql.com/doc/refman/5.7/en/date-and-time-functions.html)。

【讨论】:

  • 感谢 vigo,这非常成功。非常感谢您的帮助!
【解决方案2】:

您可以使用 substr 函数从日期中转义字符并仅添加时间,或者您也可以尝试使用 strtotime 函数来转换数据输入您从查询中获取的内容并将其放入您需要的字段中

$date2=date('Y-m-d', strtotime($date));

check the strtotime function here

另外我不认为有输入类型=“时间”所以,检查存在的输入类型

【讨论】:

猜你喜欢
  • 1970-01-01
  • 2016-07-09
  • 2020-05-27
  • 1970-01-01
  • 2011-08-03
  • 2015-10-01
  • 2017-04-22
  • 1970-01-01
  • 2018-05-31
相关资源
最近更新 更多