【问题标题】:Inconsistent date formats between browsers and database浏览器和数据库之间的日期格式不一致
【发布时间】:2017-01-10 09:14:30
【问题描述】:

我的表单上的一个字段是日期,而使用谷歌浏览器时,单击该字段时会显示一个日历框。如果我选择一个日期,格式为 DD-MM-YYYY,但当它添加到我的表中时,它显示为 YYYY-MM-DD。

我猜我的代码中遗漏了一些东西,并且在插入时将其设置为默认格式? 这是我的插入代码:

if (isset($_POST['addloan'])):

$username=$_POST['username'];

$user_query="SELECT * from loanusers where username = '$username'"; //think about how you are storing usernames in db, in this query you have to enter the username exactly how it is stored    
$userresult= mysqli_query($connection, $user_query);

$row = mysqli_fetch_array($userresult, MYSQLI_ASSOC);

$emailaddress = $row['emailaddress'];

$product=$_POST['product'];
$product_desc=$_POST['product_desc'];
$serial=$_POST['serial'];
$date_collected=$_POST['date_collected'];
$date_return=$_POST['date_return'];
$returned=$_POST['returned'];

if (isset($_FILES['loanform'])){
    $exten = pathinfo($_FILES['loanform']['name'], PATHINFO_EXTENSION);
    $loanform = $_FILES['loanform']['name'];
    $uploadfile = "loanforms/$loanform";

    if (strtolower($exten) == 'pdf'){
        move_uploaded_file($_FILES['loanform']['tmp_name'] , $uploadfile);
        $my_query="INSERT INTO loans VALUES ('','$username','$emailaddress','$product','$product_desc','$serial','$date_collected','$date_return','$loanform','$returned','')";
        $result= mysqli_query($connection, $my_query);
    } else{
        header('Location: incorrectext.php');
    }
}


    if ($result):
            header ('location: homepage.php?confirm=New loan successfully created');
        else :
            echo "<b>This didn`t work, error: </b>";
            echo mysqli_error($connection);
endif;

endif;

【问题讨论】:

  • 您的代码很容易受到 SQL 注入的影响——想象一下有人发布了用户名 '; DROP TABLE loanusers; --。请了解参数化查询以保护自己,并且不要忘记规则 #1:永远不要相信用户输入。另见:bobby tables
  • 数据库总是接受 YYYY-MM-DD 格式的日期,它不会接受 DD-MM-YYYY
  • 不是php的问题。它是db中的日期格式。
  • 尝试转换日期格式date ("Y-m-d H:i:s", strtotime($date_return));
  • @Mucca019 是的,只有 chrome 支持。您必须使用其他浏览器的插件。

标签: php date


【解决方案1】:

您的数据库表很可能设置为以YYYY-MM-DD 格式存储日期。您可以做的最好的事情是在提交表单之前和之后重新格式化日期。

// $date holds your submitted date in DD-MM-YYYY
$date = $_POST['date'];

// Reformat date
$oDate = DateTime::createFromFormat('d-m-Y', $date);

// In your query
$stmt = 'insert into table (somevalue, someother, date) VALUES ('bla', 'blabla', '".$oDate->format('Y-m-d')."')';

在检索日期时可以做同样的事情:

<?php
$date = '2016-12-10';
$oDate = DateTime::createFromFormat('Y-m-d', $date);
?>

<input type="date" value="<?= $oDate->format('d-m-Y'); ?>" />

更新

浏览器在显示日期输入方面不受限制。例如,Chrome 将在其日期选择器中使用用户的本地日期格式。在您的后端,这可能会导致一些问题。

这就是为什么我建议将您的date 更改为text 输入并使用jQuery 添加一个日期选择器。这将防止提交不一致的日期,并使您可以更好地控制提交的格式。

【讨论】:

  • 虽然日期输入字段可能显示不同的格式,但它们最后都包含相同的值:YYYY-MM-DD
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-01-20
  • 1970-01-01
  • 2016-01-15
  • 2015-11-20
  • 1970-01-01
相关资源
最近更新 更多