Catchable fatal error: Object of class DateInterval could not be converted to string in C:\xampp\htdocs\testing.php on line 30

Catchable fatal error: Object of class DateInterval could not be converted to string in C:\xampp\htdocs\testing.php on line 30

我正在计算天数并将其存储在数据库中以供进一步使用。这是我想编写的预订表格,我制作了一个类似于它的简单表格来测试天数是否会存储在数据库中,但我得到的只是这个错误。

可捕获的致命错误:class DateInterval 的对象无法转换为 C:\xampp\htdocs\testing.php 中的字符串,第 30

我只是个初学者。我已经在其他网站上检查过了,但没有什么适合我的问题。我将非常感谢所有的帮助。谢谢。

<?php

$localhost = "127.0.0.1";
$username = "root";
$password = "";
$dbase="testing";

$conn = new mysqli($localhost, $username, $password, $dbase);

//check connection
if ($conn->connect_errno) {
 die('Sorry we are having a problem.');
}


if($_SERVER["REQUEST_METHOD"] == "POST") 
{

$dateOfReserv = $_POST['dateOfReserv'];
$dateUntil  = $_POST['dateUntil'];


 $date1=date_create($dateOfReserv);
 $date2=date_create($dateUntil);
 $diff=date_diff($date1,$date2);
 $diff->format("%days");


  $sql="INSERT INTO `tbldate` (datestart, dateend, spanofdate) 
   VALUES ('$dateOfReserv', '$dateUntil', '$diff')";

  
  if ($conn->query($sql) === TRUE) {
     echo "New record created successfully";

  } 
  else {
     echo "Error: " . $sql . "<br>" . $conn->error;
  } 

  $conn->close();

   
  exit();




}


?>

<!DOCTYPE html>
<head>
<title>testing for inserting date in xampp server</title>
</head>

<body>


<form method="POST">
<ul>
 <li>
   <label for='dateOfReserv'>Date of Reservation<span>*</span></label><br />
   <input type='date' id='dateOfReserv' name='dateOfReserv' placeholder='Date of Reservation' size='40' />
 </li>
 <li>
   <label for='dateUntil'>Until?*</label><br />
   <input type='date' id='dateUntil' name='dateUntil' placeholder='End Date of Reservation' size='40' />
 </li>
 <li>
   <input type='submit' name='submitbtn' value='Send Date' />
 </li>

</ul>

</form>


</body>

</html>

你想要:

$diff = $diff->d;

而不是:

$diff->format("%days");

另请注意,您的代码容易受到 SQL 注入攻击,如果日期未格式化,您也会收到 date_create/date_diff 的错误!