0
<?php

session_start();

@mysql_connect('localhost','jk','') or die('Please Check Username or Password');
@mysql_select_db('jks') or die('error connetcing database');

$qry3="Select ID from fresh_orders";
$id=mysql_query($qry3);

$qry1="Select CurDate from fresh_orders";
$rs=mysql_query($qry1);
$row=mysql_fetch_array($rs);
$d210=$row[0];
$d21=date("Y-m-d", strtotime($d210));
echo ("  d21 = "),$d21;

$qry2="Select DueDate from fresh_orders";
$rss=mysql_query($qry2);
$row=mysql_fetch_array($rss);

$d71=$row[0];
$d7=date("Y-m-d", strtotime($d71));
echo ("  d7 = "),$d7;



$date1=date_create("$d21");
$date2=date_create("$d7");
$interval=date_diff($date1,$date2);
echo $interval->format("%R%a days");




$qry="update fresh_orders set DDays='".$interval."' where ID=".$id."";

mysql_query($qry);
echo $qry;
?>

Output is as follows:

d21 = 2016-07-20 d7 = 2016-07-10 days = -10 days

( ! ) Catchable fatal error: Object of class DateInterval could not be converted to string

It does calculate the difference properly but can't update in database! Gives the Fatal error when trying to update in database. Pls Help !

Thanks In Advance

Jainish Kothary
  • 93
  • 1
  • 10
  • If this is not legacy code, please look into alternatives to `mysql_*`. These have been deprecated and have been taken out of PHP 7. I would suggest you take a look at this line: `$qry="update fresh_orders set DDays='".$diff."' where ID=".$id."";`. – ymas Jul 10 '16 at 07:29

1 Answers1

1

You're trying to save the result of date_diff($date1,$date2) to the database. More specifically, you're trying to build a string (sql) with it.

date_diff produces a DateInterval type, which can't be used as a string - that's why you need to call ->format on it when you echo it. You also need to call ->format('%d') where you're building the sql statement.

Your output probably doesn't say days = -10 days, but something like days = -10ays. That's because you're formatting the interval in a weird way - take a look at http://php.net/manual/en/dateinterval.format.php

  • Thanks a lot for giving a very perfect explanation. I tried correcting errors just as mentioned by you.But still can't update in database. Is there anyway I can do it? $date1=date_create("$d21"); $date2=date_create("$d7"); $interval=date_diff($date1,$date2); echo $interval->format("%R%a days"); – Jainish Kothary Jul 17 '16 at 07:52