php日期格式返回01-01-1970
在我的php代码中,我在数据库中插入了一些数据。其中之一就是日期。我想以2016年8月27日的格式显示,但我得到了1970年1月1日的回复 这是我的密码php日期格式返回01-01-1970,php,mysql,date,Php,Mysql,Date,在我的php代码中,我在数据库中插入了一些数据。其中之一就是日期。我想以2016年8月27日的格式显示,但我得到了1970年1月1日的回复 这是我的密码 <?php include("./init.php"); if(isset($_POST['submit'])){ $post_game = $_POST['game']; $time = strtotime($_POST['date']); $post_date = date("d-m-Y", strtotime($ti
<?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>";
}
}
?>
我的php版本是:5.6.23请在查询中使用Now()插入当前日期。NOW()返回当前日期和时间。
$time = strtotime($_POST['date']);
^-integer ^---string
$post_date = date("d-m-Y", strtotime($time));
^^^^^^^---useless duplicate call, since you JUST did this anyways
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>";
}
}
?>
你的问题是:
$time = strtotime($_POST['date']);
$post_date = date("d-m-Y", strtotime($time)); //why call strtotime again?
第二次调用strotime时,您向它提供了一个时间戳(第一次调用的结果),但它需要一个日期字符串。因此,它无法解析输入,并返回无效时间。只需将上面的两行替换为:
$time = strtotime($_POST['date']);
$post_date = date("d-m-Y", $time);
strotime失败,返回boolean false,将类型转换为整数0,即1970年1月1日。你很容易受到攻击,你所有的代码都简单地假设没有任何东西会失败,现在你正在为此而痛苦。永远不要假设成功。始终假设失败,检查失败,并将成功视为惊喜。另请注意,修复SQL注入漏洞。除此之外,为什么要将
date
作为非date
对象插入数据库,插入数据库时,日期格式应为Y-m-d
。警告:使用mysqli
时,应使用和将用户数据添加到查询中。不要使用字符串插值或串联来完成此操作,因为您已经创建了严重的错误。永远不要将$\u POST
或$\u GET
数据直接放入查询中,如果有人试图利用您的错误,这可能非常有害。这很好。我写了一个样本日期,给了我这个。2016-07-18 19:14:18. 但我想抽时间。
$time = strtotime($_POST['date']);
$post_date = date("d-m-Y", strtotime($time)); //why call strtotime again?
$time = strtotime($_POST['date']);
$post_date = date("d-m-Y", $time);