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

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.
How can I fix this? I am having a hard time getting a var_dump() 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!

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
}

Related

Select a SubArray if today date is between 2 keys value

I have a multidimensional array like this:
$array = array(
0 => array(
'name' => 'first element',
'start' => '30/04/2015',
'end' => '30/06/2015'
),
1 => array(
'name' => 'second element',
'start' => '01/07/2015',
'end' => '30/09/2015'
),
2 => array(
'name' => 'fourth element',
'start' => '01/10/2015',
'end' => '15/12/2015'
)
);
I need to select one array subarray (item) based on the today date.
today date must be between start date and end date keys.
In the end I would like to have this:
$selected_subarray = array (
'name' => 'first element',
'start' => '30/04/2015',
'end' => '30/06/2015'
)
I use to check between two dates like this:
function check_if_in_range($start_date, $end_date, $today_date)
{
$start_d = strtotime($start_date);
$end_d = strtotime($end_date);
$today_d = strtotime($today_date);
return (($today_d >= $start_d) && ($today_d <= $end_d));
}
I tryed to follow suggestions from this question How to search by key=>value in a multidimensional array in PHP
but if I'm able to filter for a key = value, I'm not able to do the same using the "check_if_in_range" function.
You do know that 30/06/2015 is invalid date, and strtotime() will return false? See here. Format mm/dd/yyyy is an American month, day and year. So your format is non-standard.
Best way is to convert it to standard format, and then use strtotime()example or just use DateTime::createFromFormat()example.
After you learn how formating and converting dates works, then you can just do simple foreach loop, and break on first found result. Here is a little demo.
Try something like the following
foreach($array as $key => $value) {
if(check_in_range($value['start'], $value['end'], $today_date)) {
$selected_subarray = $value;
}
}

Retrieve data based on year and month in cakephp

I am trying to create a get statements function and I have some problems defining the date range.
The data will be passed via get method in the following format: ?year=yyyy&month=mm
The relevant column of the table has datetime type (2012-02-01).
I checked the TimeHelper class and more particularly the TimeHelper::daysAsSql($begin, $end, $fieldName, $timezone = NULL) but i am not sure if it applies for this case.
I was thinking if i can create a date in the format of Y-m using the two variables year and month and then use it in the conditions for retrieving the data but I am sure there is a more efficient and proper way. Could anyone help?
$user_id = $Client['Client']['id'];
$year = $this->request['url']['year'];
$month = $this->request['url']['month'];
//$date_created = date('Y-m');
if (!empty($user_id) && (!empty($date_created))) {
$Reports = $this->Report->find('all', array(
'fields' => array('amount','currency','date_created','invoice_no'),
'conditions' => array(
'Report.client_id'=> $user_id,
'Report.date_created >=' => $date_created,
'Report.date_created <=' => $date_created
),
)
);
MONTH(dateColumn) Returns an integer that represents the month of the specified date.
YEAR(dateColumn) Returns an integer that represents the year of the specified date.
InCakephp use as
$user_id = $Client['Client']['id'];
$year = $this->request['url']['year'];
$month = $this->request['url']['month'];
//$date_created = date('Y-m');
if (!empty($user_id) && (!empty($date_created))) {
$Reports = $this->Report->find('all', array(
'fields' => array('amount','currency','date_created','invoice_no'),
'conditions' => array(
'Report.client_id '=> $user_id,
'MONTH(date_created ) >='=> $month,
'YEAR(date_created ) <=' => $year
),
)
);

Google charts column graph from MySql database

The real question is how do I populate a Google charts datatable form a MySql query when a date is used for the first column?
I am trying to create a column chart using the Google Charts API. The problem is that the data is time series data. There are many dates represented. The way that this is done to create the data table is to assign column 0 to the date and each subsequent column represents the data being measured. That information is derived from the documentation. I just can't figure out how to get the data to assign to the subsequent columns. I have researched this extensively now and there are some answers that are close, but I can't make them work for this. Here is the code that is currently generating my chart data table:
$invArr = array('cols' => array(
array('label' => 'date', 'type' => 'date'),
array('label' => 'SKU', 'type' => 'number')),
'rows' => array());
while($row = mysql_fetch_row($query)) {
$invArr['rows'][] = array('c' => array(array('v' => $row[0]), array('v' => $row[1])));
}
I understand from the Google charts documentation that column 0 is always the date for continuous data. Each subsequent column is the data that is being measured, in this case ths SKU numbers. I need to have the first array in each row represent the date and the subsequent arrays represent the qtyoh data. I don't know how to do that.
I researched this for several days and I was finally able to solve the problem by piecing together answers to many different questions.
I started by querying the distinct dates and placing them into an array. The way this is done is very important because the date is a string when json encoded. It is important to parse it out and pass it in the Date(year,month,day) format exactly. It is also important that later on you use a variable to represent the date.
$dateArray = array();
while($row = mysql_fetch_row($queryDates)) {
$dtArray = explode('-',$row[0]);
$day = (int) $dtArray[1];
$month = ((int) $dtArray[0])-1;
$year = (int) $dtArray[2];
$dateArray[] = "Date($year, $month, $day)";
}
I then set up the columns for the table by looping through a query of the SKU's.
$invArr = array(
'cols' => array(
array('label' => 'Date', 'type' => 'date')
)
);
while($row = mysql_fetch_row($querySkus)) {
$invArr['cols'][] = array('label' => $row[0], 'type' => 'number');
}
I then query the quantities and place them into an array. I then loop through each value and populate the table array ($inVarr).
$quantities = array();
while($row = mysql_fetch_row($queryQty)) {
$quantities[] = (int) $row[0];
}
$qtyCounter = 0;
for($i=0;$i<count($dateArray);$i++) {
$invArr['rows'][] = array(
'c' => array(
array('v' => $dateArray[$i]),
array('v' => $quantities[$qtyCounter]),
array('v' => $quantities[$qtyCounter+1]),
array('v' => $quantities[$qtyCounter+2])
)
);
$qtyCounter=$qtyCounter+3;
}
I can then just echo the json encoded array which will return the data for the data table.
echo json_encode($invArr);
I believe that this is a bit clunky, but it works.

insert multiple rows in a saveall in cakephp

i'm newbie in Cake and wodering how to insert multiple rows in a single saveall function,
i got this table,
CREATE TABLE IF NOT EXISTS `dates` (
`date` varchar(10) COLLATE utf8_unicode_ci NOT NULL
)
what i'm trying to do is let user select start date and end date using JQuery calander, once submit all the dates between this range will be saved into database, i already got the array of dates eg:
`array(
(int) 0 => '5/8/2013',
(int) 1 => '6/8/2013',
(int) 2 => '7/8/2013',
(int) 3 => '8/8/2013',
)
`
then my controller looks like this:
public function index(){
if ($this->request->is('post')) {
$this->Date->create();
$data = array();
$data['dates']=array();
$startDate = $this->request->data['Date']['from'];
$endDate = $this->request->data['Date']['to'];
$datesBlocked = $this->loopDates($this->request->data['Date']['from'],$this->request->data['Date']['to']);
$data['dates'][] = $this->request->data['Blockdate']['from'];
$data['dates'][] = $this->request->data['Blockdate']['to'];
/*foreach($datesBlocked as $data) {
$data['dates'][] = $data;
}*/
if($this->Date->saveAll($data)) {
$this->Session->setFlash(__('done'));
if ($this->Session->read('UserAuth.User.user_group_id') == 1) {
// $this->redirect("/manages");
}
}
}
public function loopDates($from,$to){
$blockdates = array();
$start = strtotime($from);
$end = strtotime($to);
debug($start);
$counter = 0;
for($t=$start;$t<=$end;$t+=86400) {
$d = getdate($t);
$blockdates[$counter++] = $d['mday'].'/'.$d['mon'].'/'.$d['year'];
}
debug($blockdates);
return $blockdates;
}
issue was i can't get foreach work, if i uncomment the foreach, i got error said Illegal string offset 'dates' , so i commented that and try to only add the start date and end date to the array to see if that works, then i got another error said.
`array(
'dates' => array(
(int) 0 => '08/05/2013',
(int) 1 => '09/05/2013'
)
)
`
Notice (8): Array to string conversion [CORE\Cake\Model\Datasource\DboSource.php, line 1005]Code
cuz i'm trying to insert 2 values into one field...i know it should be sth like
`array(
'dates' => array( (int) 0 => '08/05/2013',
)
'dates' => array((int) 1 => '09/05/2013'
))
`but can't figure out how to do it. Any help would be much appreciate!!!!
The structure you'll want your array to save multiple dates using saveAll() is this:
array(
'Date' => array(
0 => array(
'date' => '08/05/2013',
),
1 => array(
'date' => '09/05/2013',
)
),
)
I know that this is a little late, but to write multiple rows in a loop, you have to proceed the save with a create().
eg:
foreach($items as $lineItem){
$this->Invoice->create();
$this->Invoice->save(array(
'user_id'=>$property['User']['id'],
'invoice_id'=>$invId['Invoices']['id'],
'item_id'=>$lineItem['item_number'],
'quantity'=>$lineItem['quantity'],
'price'=>$lineItem['mc_gross']
);
}
Just thought it was worth mentioning, hopefully it will help someone.

Insert Date into database table using Zend framework insert method

I have the foll code as:
$table_project_win = new Application_Model_DbTable_AfterWinProject();
$data_win = array(
'project_id' => $project_id,
'project_name' => $project,
'project_type_id' => $pro_type,
'start_date' => $dateStart,
'end_date' => $dateEnd,
'project_size' => $size,
'project_description' => $pro_des
);
$table_project_win->insert($data_win);
Here I get the $dateStart and $dateEnd variabled using as:
$dateStartt = $this->_getParam('dateStart');
echo 'date Start: '.$dateStartt;
$dateStart='"'.$dateStartt.'"';
$dateEndd = $this->_getParam('dateEnd');
$dateEnd='"'.$dateEndd.'"'
By using getParam I get the value of the date that the user has given input But when i will insert it into the database I use as
$dateStart='"'.$dateStartt.'"';
$dateEnd='"'.$dateEndd.'"'
But in the database table the value for date inserted is '0000-00-00' While when I echo the $dateStart which I have got through getParam It gives the correct value as '2012-12-11'.What is the reason of it??What Should I do??
replace $dateStart='"'.$dateStartt.'"';
with
$dateStart= $dateStartt ;
or
$dateStart='`'.$dateStartt.'`';

Categories