Liz Banach Liz Banach - 3 months ago 15
MySQL Question

PHP error when using date_diff() function within DataTables $columns array

Forgive me, this is a long one. I want to give all the background for this question.

I am using DataTables server-side processing for a project. My goal is to utilize the

echo
function to
echo
the number of days between today's date and dates in a column of my database called CreatedDate, which is a DateTime type.

I was trying to get the basic functionality working outside of DataTables first, and the function below works as intended, and outputs an
$current_date
of the number of days between
$date
and
$date
as: "16 days live", "15 days live", etc.:

$sql = "SELECT CreatedDate FROM Estimates";
$result = $conn->query($sql);

if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
$created_date = $row["CreatedDate"];
$date = new DateTime($created_date);
$current_date = new DateTime();
$diff = date_diff($date, $current_date);
echo $diff->format('%d days live');
}
} else {
echo "No results";
}


In my DataTables
$columns
array, I am trying to achieve the same effect:

// date variable
$created_date = 'CreatedDate';
$current_date = new DateTime();

// array of database columns which should be read and sent back to DataTables.
// the 'db' parameter represents the column name in the database, while the 'dt'
// parameter represents the DataTables column identifier.
$columns = array(
array( 'db' => 'Client', 'dt' => 0 ),
array( 'db' => 'EstimateNumber', 'dt' => 1 ),
array( 'db' => 'Status', 'dt' => 2 ),
array( 'db' => 'CurrentEstimateTotal', 'dt' => 3 ),
array(
'db' => $created_date,
'dt' => 4,
'formatter' =>
function ($created_date, $row) use ($current_date) {
$date = new DateTime($created_date);
$diff = date_diff($date, $current_date);
echo $diff->format('%d days live');
}
)
);


I keep recieving an error of:

PHP Notice: Trying to get property of non-object.


Which I believe is in reference to either the
$date
or
of the
variables. How can I fix this? I am having a hard time getting a
$date
of the
$created_date
and
$date
variables within the DataTables array to see what the problem is.

For more information about DataTables server-side processing, I am using this template as a base for my DataTables script. The DataTables script also uses this helper class. Thank you in advance!

Answer

Just return your string from callback.

'formatter' =>
        function ($created_date, $row) use ($current_date) {
        $date = new DateTime($created_date);
        $diff = date_diff($date, $current_date);
        return $diff->format('%d days live'); //That will solve your problem
     }