I am testing out whether I can get and display the duration that is between two dates based on post. These two dates are called from the database.
This is before I clicked the "Update Contract" .
This is after I clicked the "Update Contract" .
Php:
<?php
require("config.php");
$id = filter_input(INPUT_GET, 'id');
error_reporting( ~E_NOTICE );
if(isset($_POST['edit']) ){
$startdate = date('Y-m-d', strtotime($_POST['startdate']));
$expdate = date('Y-m-d', strtotime($_POST['expdate']));
$diff = abs(strtotime($expdate) - strtotime($startdate));
$years = floor($diff / (365*60*60*24));
$months = floor(($diff - $years * 365*60*60*24) / (30*60*60*24));
$days = floor(($diff - $years * 365*60*60*24 - $months*30*60*60*24)/ (60*60*24));
$upd= "UPDATE `contracts` SET `startdate` = ?, `expdate` = ? WHERE `id` = ?";
$stmt = $con->prepare($upd);
$stmt->bind_param("ssi",$startdate,$expdate,$id);
$stmt->execute();
if ($stmt->errno){
echo "FAILURE!!! " . $stmt->error;
} else {
$successMsg = "Contract Successfully Updated!";
}
$stmt->close();
}
printf("%d years, %d months, %d days\n", $years, $months, $days);
?>
Form:
<form method="post" action="">
<?php
if(isset($successMsg)){
?>
<div class="alert alert-success">
<strong><?php echo $successMsg; ?></strong>
<?php
}
?>
<?php
$id = filter_input(INPUT_GET, 'id');
$sql = "SELECT * FROM contracts WHERE `id` = $id";
$result = $con->query($sql);
$row = $result->fetch_assoc();
?>
<label>Start Date</label>
<input type="date" name="startdate" value="<?php echo $row['startdate']; ?>"/>
<label>Expiry Date</label>
<input type="date" name="expdate" value="<?php echo $row['expdate']; ?>"/>
<button type="submit" class="btn btn-success btn-md" name="edit">
<span class="glyphicon glyphicon-pencil"></span> Update Contract
</button>
</form>
The Problems are:
Answer for second question:
make use of the native DateTime Class and it's related DateInterval :
<?php
$startdate=new DateTime($_POST['startdate']);
$expdate=new DateTime($_POST['expdate']);
$diff=$expdate->diff($startdate);
print_r( $diff );
// or
printf("%d years, %d months, %d days\n", $diff->y, $diff->m, $diff->d);
// for database input you'll have to format the dates like so:
echo $startdate->format('Y-m-d');
The solution to your first question is just about restructuring your code.
I suppose this is all in one php-file.
$startdate = $row['startdate']
;)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.