I'm having problems with the handling of a date format. In my code, I try to calculate an expiration date starting from a specified date and then to save it in my MySQL database.
The problem is that I always receive this error:
Fatal error: Call to a member function add() on a non-object
and I'm not able to solve it. For example, it works if I manually replace $scadenza_contratto with a specific date, for example:
$expiration_date = DateTime::createFromFormat('Y-m-d', '2016-02-10');
In this case, it works, but I need to receive date from $scadenza_contratto. Can you help me, please? This is my code:
if($anno > 0 && $giorno > 0 && $mese >0){
$scadenza_contratto = $anno."-".$mese."-".$giorno;
//$scadenza_contratto = date('Y-m-d', strtotime("+{$scadenze} months", strtotime($scadenza_contratto)));
$sql1 = "SELECT * FROM scadenze WHERE contratto_id=$contratti_id";
$row1 = mysql_fetch_assoc( mysql_query($sql1) );
echo "tipo ".$row1['tipo'];
if(!$row1){
for ($m = $scadenze; $m <=60 ; $m += $scadenze){
//add $m to activation_date
$scadenza_contratto = $anno."-".$mese."-".$giorno;
$expiration_date = DateTime::createFromFormat('Y-m-d', '$scadenza_contratto');
$expiration_date->add(new DateInterval('P'.$m.'M'));
//do something with $expriration_date
echo "Expire: ".$expiration_date->format('Y-m-d'). "<br>";
$expiration_db = $expiration_date->format('Y-m-d H:i:s');
$time=time();
//mysql_query("INSERT INTO contratti (nome_area) VALUES('$nome_area','$giorno','$mese','$file_name','$attiva','$id_voce','$nome_azienda','$time')");
mysql_query("INSERT INTO scadenze (nome_azienda,nome_voce,contratto_id,nome_area,scadenza,tipo,created_date) VALUES ('$nome_azienda','$nome_voce','$contratti_id','$nome_area','$expiration_db','$scadenze','$time')");
}
}
}
$scadenza_contrattobefore to use in$expiration_date = DateTime::createFromFormat('Y-m-d', '$scadenza_contratto');$meseor$giornohave values less than 10 (which is quite possible as you're treating them as integer values rather than as two-character strings), then your format mask will need to be'Y-n-j'rather than'Y-m-d'$scadenza_contratto; ($expiration_date = DateTime::createFromFormat('Y-m-d', '$scadenza_contratto');as this will treat it as a string literal.... you're trying to convert the string literal'$scadenza_contratto'to a date, rather than the value of the string variable$scadenza_contratto