【问题标题】:PHP Obtain Textual Month, Day and Year from input fieldPHP 从输入字段中获取文本的月、日和年
【发布时间】:2014-10-19 05:34:03
【问题描述】:

我在输入字段中有一个文本的月、日和年,我想将其转换为稍后将插入到 MySQL 表中的“日期”字段中的日期。

来自 HTML 输入字段的文本月、日和年:“2014 年 8 月 25 日”。

PHP:

$time_cell_row = 1;
$time_cell_column = 1;

echo "<form name='timesubmit" . $time_cell_row . "' action='enter_time.php?action=timesubmit" .$time_cell_row . "' method='post'>";  

$todays_date = strtotime("today");  // 
$FormattedCurrDate = date('M d, Y', $todays_date);  // Converts to "Aug 25, 2014"

echo "<th><input name=daycell1 type=text value=" . $FormattedCurrDate . "<disabled /></th>";

// The above echo statement displays "Aug" in a table cell instead of "Aug 25, 2014"

echo "<td><input name=submit_time" . $time_cell_row . $time_cell_column . " type=submit></input></td>";
echo  "</form></tr>";


$date1 = $_POST['daycell1'];  // null 
echo "Date from input field: " . $date1; // Nothing is displayed from $date1 since is null

          echo "<br>"; 

为什么 $_POST['daycell1'] 显示为 null 而不是输入“2014 年 8 月 25 日”?

【问题讨论】:

  • 考虑表中特定列的数据类型
  • 仅供参考:&lt;input&gt; 标签是无效标签,因此它们没有&lt;/ 结束标签,请改用value="your php variable"
  • echo "&lt;th&gt;&lt;input name=daycell1 type=text value=" . $FormattedCurrDate . "&lt;disabled /&gt;&lt;/th&gt;"; 不要使用 disabled 属性,使用 readonly 并删除多余的 &lt;
  • 放置变量 '$FormattedCurrDate' 并将 'disabled' 更改为 'readonly' 使其工作!现在下一部分是如何将此字符串“2014 年 8 月 25 日”转换为日期,以便将其插入 MySQL 表中?

标签: php html mysql date


【解决方案1】:

当然,$date1null,因为您还没有提交表单,所以 $_POST['daycell1'] 在第一次加载时仍然未定义。

&lt;input /&gt; 标签是无效标签,它们没有结束标签。如果您希望它们包含值,请使用 value="" 属性。

不要使用disabled 属性。所有带有disabled 属性的输入标签都不会包含在$_POST 中。请改用readonly

// defaults to current day
$FormattedCurrDate = date('M d, Y');

echo '<form method="POST">';
    echo '<table><tr>';
        echo "<th><input name='daycell1' type='hidden' value='$FormattedCurrDate' /></th>";
        echo '<td><input type="submit" name="submit" /></td>';
    echo '</tr></table>';
echo '</form>';

// if submit button is pressed
if(isset($_POST['submit'])) {
    $date = $_POST['daycell1']; // assign the hidden tag value to variable
    echo $date;
}

由于缺少右引号,日期被截断。

echo "<th><input name=daycell1 type=text value='" . $FormattedCurrDate . "' /></th>";
                                           //  ^ quotes                   ^ quotes

旁注:开发时始终开启错误报告

error_reporting(E_ALL);
ini_set('display_errors', '1');

【讨论】:

  • 将表单放在代码上方肯定有帮助,我将那行代码放在错误的位置。现在的问题是当我设置: echo ""; ---> 表格单元格现在是空白的,当我检查元素时,显示的是:
  • @JeffP。发生什么了? The problem now is when I set:?你必须比这更具体。我猜不出你那边发生了什么。
  • @JeffP。这是一个技巧问题吗?哈哈:D。它应该是空白的。它是一个隐藏的输入标签,如果您不想看到它,请改用type="text"
  • @JeffP。更新您的问题并添加您当前正在使用的代码,顺便说一下codepad.viper-7.com/8nwyU1,它很可能是您的echo 上的引用问题
  • 漂亮的代码风格。 +1 我会将第一个变量保留为小写 f
猜你喜欢
  • 2016-07-27
  • 1970-01-01
  • 2019-11-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-02-16
  • 2015-09-06
相关资源
最近更新 更多