将Java的时间戳字符串与PHP的时间戳日期进行比较

4

我有一个Java字符串表示的时间戳,想要与SQL进行比较并添加数据,但出现了解析错误,不知道为什么。请问有什么解决方法吗?

<?php
if($_SERVER['REQUEST_METHOD']=='POST'){
//Getting values
$number = $_POST['number'];
$type = $_POST['type'];
$date = $_POST['date'];
$content = $_POST['content'];
$start = strtotime("now");
$end = strtotime("-7 days");
while($start->format('U') > $date->format('U') > $end->format('U')){

$sql = "INSERT INTO message_detail (number,type,date,content) VALUES  ('$number','$type','$date','$content')";

//Importing our db connection script
require_once('connect.php');

//Executing query to database
if(mysqli_query($con,$sql)){
echo 'Entry Added Successfully';
}else{
echo 'Could Not Add Entry';
}
}
//Closing the database 
mysqli_close($con);
}
?>

我看到你的代码有一些问题。首先,你在循环中包含了数据库连接脚本;其次,你直接将变量嵌入 SQL 中,这样会导致 SQL 注入攻击的风险。 - Professor Abronsius
1个回答

0

你的代码存在一些问题,例如:

  • strtotime()函数返回一个整数时间戳,而不是DateTime对象,因此您不能像这样调用format()方法。

    $start = strtotime("now");
    $start->format('U');
    //等等都是错误的
    

    相反,创建一个DateTime对象,然后调用它的format()方法,就像这样:

    $start = new DateTime("now");
    $start->format('U');
    //等等。
    
  • 现在来看看你的问题,

    它给出了解析错误

    这是因为你的while条件,

    while($start->format('U') > $date->format('U') > $end->format('U')){ ...
          ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
    

    也许,你想做这样的事情:

    while($start->format('U') < $date->format('U') &&  $date->format('U') > $end->format('U')){
    
        //你的代码
    
    }
    


侧记:

  • 在每次循环迭代中包含连接处理程序是没有意义的,因此将此语句 require_once('connect.php'); 移到你的 while 循环之外。

  • 学习 预处理语句,因为现在你的查询容易受到 SQL 注入攻击。还可以查看 如何在 PHP 中防止 SQL 注入


编辑:

我想要在录入时间后仅输入最近7天的数据……

如果这是您的要求,则可以使用 strtotime() 函数或 DateTime 类来实现,

(1) 使用strtotime()函数

// your code

$content = $_POST['content'];
$start = strtotime("-7 days");
$date = strtotime($date);
$end = strtotime("now");

使用 while 循环没有意义,一个简单的 if 条件就足够了。

if($start <= $date &&  $end >= $date){

    // your code

}

(2)使用 DateTime 类

// your code

$content = $_POST['content'];
$start = new DateTime("-7 days");
$date = new DateTime($date);
$end = new DateTime("now");

使用 while 循环没有意义,一个简单的 if 条件就足够了。

if($start->format('U') <= $date->format('U') &&  $end->format('U') >= $date->format('U')){

    // your code

}

谢谢你的回答,Rajdeep,但我想输入从录入时间起仅过去7天的数据,所以我必须使用strtotime(),是否还有其他可用的方法...? - Hiren Gujarati
@HirenGujarati 我已经编辑了我的答案。请查看我的答案的 已编辑 部分。 - Rajdeep Paul
嘿@rajdeep,如果(mysqli_query($con,$sql))在这一行出错了,会显示以下错误:mysqli_query(): Empty query in <b>/home/u336100496/public_html/call_detail/insert.php</b> on line <b>19</b><br /> 无法添加条目,连接成功<br /> - Hiren Gujarati
@HirenGujarati,你是否像这样在if块内构建了查询:$sql = "INSERT INTO message_detail ...?我觉得不是。 - Rajdeep Paul

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接