我有一个 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);
}
?>
最佳答案
您的代码几乎没有问题,例如:
strtotime()
函数返回一个整数时间戳,而不是DateTime
对象,所以你不能像这样调用format()
方法。$start = strtotime("now"); $start->format('U'); // etc. are wrong
相反,创建一个
DateTime
对象,然后调用它的format()
方法,如下所示:$start = new DateTime("now"); $start->format('U'); // etc.
现在谈到你的问题,
it's giving a parse error
那是因为你的
while
条件,while($start->format('U') > $date->format('U') > $end->format('U')){ ... ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
也许,你想做这样的事情:
罢工>while($start->format('U') < $date->format('U') && $date->format('U') > $end->format('U')){ // your code }
<罢工>罢工>
旁注:
在循环的每次迭代中都包含连接处理程序是没有意义的,因此请在
while之外使用此语句
循环。require_once('connect.php');
了解 prepared statements因为现在您的查询容易受到 SQL 注入(inject)的影响。另见 how you can prevent SQL injection in PHP .
编辑:
i want to enter a data of only last 7 days from entry time...
如果这是您的要求,那么您可以使用 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
}
关于java - 将 java 纪元字符串与 php 纪元日期进行比较,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39305342/