Compare the Java era string with the PHP era date

Here I have a Java string era date. I want to compare and add data

<?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);
}
?>

Solution

There are few problems with your code, such as:

>The strtotime () function returns an integer timestamp instead of a datetime object, so you can't call the format () method like this

$start = strtotime("Now");
$start->format('U');
// etc. are wrong

Instead, create a DateTime object and call its format () method as follows:

$start = new DateTime("Now");
$start->format('U');
// etc.

>Now let's talk about your problem,

That's because of your conditions,

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

Maybe you want to do something like this:

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

    // your code

}

Caption of the picture:

>The connection handler is not included in each iteration of the loop, so use this sentence require_ once(‘connect.PHP’); Outside your while loop. > Understand prepared statements because your queries are now vulnerable to SQL injection See also how you can prevent SQL injection in PHP

Edit:

If this is your requirement, you can use the strtotime () function or the datetime class to do this,

(1) Use the strtotime() function

// your code

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

And there is no need to use a while loop. A simple if condition is OK,

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

    // your code

}

(2) Use datetime class

// your code

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

And there is no need to use the while loop,

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

    // your code

}
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>