【问题标题】:php date format returns 01-01-1970php 日期格式返回 01-01-1970
【发布时间】:2016-07-18 16:02:09
【问题描述】:

在我的 php 代码中,我在我的数据库中插入了一些数据。其中之一是日期。我想以 27-08-2016 的格式显示,但我返回 01-01-1970

这是我的代码。

<?php 
include("./init.php");

if(isset($_POST['submit'])){

 $post_game = $_POST['game'];

 $time = strtotime($_POST['date']);

 $post_date = date("d-m-Y", strtotime($time));

if($post_game==''){

    echo "<script>alert('Please fill in all fields')</script>";
    exit();
    }
else {

    $insert_game = "insert into last_game (game,date) values ('$post_game','$post_date')";

    $run_posts = mysqli_query($con,$insert_game); 

        echo "<script>alert('Post Has been Published!')</script>";

        echo "<script>window.open('index.php?last_game_details','_self')   
   </script>";

     }

   }

?> 

关键是:

 $post_date = date("d-m-Y", strtotime($time));

而我的php版本是:5.6.23

【问题讨论】:

  • strtotime 失败,返回布尔值 false,将类型转换为整数 0,即 1970 年 1 月 1 日。你很容易受到sql injection attacks 的攻击,你所有的代码都只是假设没有任何事情会失败,现在你正在为此受苦。永远不要永远假设成功。始终假设失败,检查失败,并将成功视为惊喜。
  • 旁注,修复SQL注入漏洞。
  • 除此之外,为什么要将date 作为非date 对象插入数据库,日期格式应为Y-m-d 以插入数据库
  • 警告:使用mysqli 时,您应该使用parameterized queriesbind_param 将用户数据添加到您的查询中。 请勿使用字符串插值或连接来完成此操作,因为您创建了严重的SQL injection bug切勿$_POST$_GET 数据直接放入查询中,如果有人试图利用您的错误,这可能会非常有害。

标签: php mysql date


【解决方案1】:
 $time = strtotime($_POST['date']);
    ^-integer             ^---string

$post_date = date("d-m-Y", strtotime($time));
                                ^^^^^^^---useless duplicate call, since you JUST did this anyways

【讨论】:

    【解决方案2】:

    请在查询中使用 Now() 插入当前日期。 NOW() 返回当前日期和时间。

    if(isset($_POST['submit'])){
    
     $post_game = $_POST['game'];
    
     $time = strtotime($_POST['date']);
    
     $post_date = date("d-m-Y", strtotime($time));
    
    if($post_game==''){
    
        echo "<script>alert('Please fill in all fields')</script>";
        exit();
        }
    else {
    
        $insert_game = "insert into last_game (game,date) values ('$post_game',NOW())";
    
        $run_posts = mysqli_query($con,$insert_game); 
    
            echo "<script>alert('Post Has been Published!')</script>";
    
            echo "<script>window.open('index.php?last_game_details','_self')   
       </script>";
    
         }
    
       }
    
    ?> 
    

    要检索所需的日期格式,请使用 php

    `echo date_format($date,"Y-m-d ");` 
    

    【讨论】:

    • 那很好。我放了一个示例日期并给了我这个。 2016-07-18 19:14:18。但我想抽出时间。
    【解决方案3】:

    你的问题在这里:

     $time = strtotime($_POST['date']);    
     $post_date = date("d-m-Y", strtotime($time)); //why call strtotime again?
    

    第二次调用strtotime,你给它一个时间戳(第一次调用的结果),但它需要一个日期字符串。结果,它无法解析输入并返回无效时间。只需将上面的两行替换为:

     $time = strtotime($_POST['date']);    
     $post_date = date("d-m-Y", $time);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-01-16
      • 1970-01-01
      • 1970-01-01
      • 2023-03-03
      • 1970-01-01
      • 2012-02-17
      • 2011-09-09
      相关资源
      最近更新 更多