insert multiple rows in a saveall in cakephp - php

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.

Related

Find all documents in mongodb

I want to display all documents (select *) with sub-documents in PHP.
I know how to query all find() but I have no idea how to do it when I have sub-documents. I don't know if there's something like find() or I need to make loops fo every sub-documents that I'd have.
This would be the code
$mongodatabase->insertOne(
['name' => 'Alex',
'surname' => 'Turner',
'country' => 'England',
'birth' => array(
'day' => 6,
'month' => 'january',
'year' => 1986
),
]);
Something easy, just to learn. When I try a var_dump of day I get Undefined index and NULL.
$client = new MongoDB\client;
$db = $client->database;
$mongodatabase = $db->document;
$document = $mongodatabase->find();
foreach ($document as $doc) {
var_dump($doc->day);
}
However, I'd like to query all.
Use $exists - It helps us in identifying the elements which are not empty
db.collection_name.find({
"birth.day" : {
$exists : true
}
});
If you need to check not null and empty, then we need to use $type together with $exists, $type can be passed with different values and 10 is for null check
db.collection_name.find({
"birth.day" : {
$not : { $type : 10 },
$exists : true
}
});
when u find the exactly data from mongoldb u can use the shelter to limit the field
eg:
db.xxxxx.find(
{'status':'DELIVRD'}
);

How to subtract two datetime in mongo php

Here I did the query for subtract but the result am getting null value. Is this correct way for subtract two datetime in project?
Code:
$arguments = array(
array(
'$project' => array(
'updatetime_difference' => array('$subtract' =>array('ISODate(2015-05-30T10:01:58.000Z)','$update_date')),
)
)
);
$result = $db->aggregate($arguments);

Return a 4-dimension array with SQL and Codeigniter

I need to do a query and get certain kind of data. I have 2 tables, users and connections, I need to get per user how many times he/she connected per month and year.
users connections
........... ................
john 10/02/2014
john 15/02/2014
john 03/01/2015
john 06/02/2015
Is there a chance to get this info in this format:
john=>
[0]=>2014
[0]=>02
'total' =>2
[1]=>2015
[0]=>01
'total' => 1
[1]=>02
'total' => 2
[2]=>03
'total'=> 1
I'm using Codeigniter and also PHP.
Answering to #CodeGodie what I've done so far is:
public function getPeriodicity(){
$this->db->select('u.vusr_user, extract (MONTH from (to_timestamp(c.vuc_log_in))) as month, extract (YEAR from (to_timestamp(c.vuc_log_in))) as yearly, COUNT(c.vuc_log_in)');
$this->db->from('vts_users_conn c');
$this->db->join('vts_users u', 'c.vuc_vusr_id = u.vusr_id');
$this->db->group_by('u.vusr_user, month, yearly','asc');
$query = $this->db->get();
return $query->result_array();
}
Assuming you are using Codeigniter's $this->db->result_array() to obtain your database results, your initial array will look like this:
$res = array(
array(
"name" => "john",
"date" => "10/02/2014"
),
array(
"name" => "john",
"date" => "15/02/2014"
),
array(
"name" => "john",
"date" => "03/01/2015"
),
array(
"name" => "john",
"date" => "06/02/2015"
),
array(
"name" => "john",
"date" => "06/03/2015"
)
);
In order to change this array to your desired output, I would do the following:
foreach ($res as $row) {
$date_arr = explode("/", $row['date']);
$n = $row['name'];
$y = $date_arr[2];
$m = $date_arr[1];
if (!isset($final[$n]))
$final[$n] = array();
if (!isset($final[$n][$y]))
$final[$n][$y] = array();
if (!isset($final[$n][$y][$m])) {
$final[$n][$y][$m] = array("total" => 1);
} else {
$final[$n][$y][$m]["total"] = $final[$n][$y][$m]["total"] + 1;
}
}
If you var_dump your final result (var_dump($final)), you will get the following:
array (size=1)
'john' =>
array (size=2)
2014 =>
array (size=1)
'02' =>
array (size=1)
'total' => int 2
2015 =>
array (size=3)
'01' =>
array (size=1)
'total' => int 1
'02' =>
array (size=1)
'total' => int 1
'03' =>
array (size=1)
'total' => int 1
Hope this helps.
As a general rule, if you can access the data and see in your mind how you want that data to look, then it's pretty much possible to get it to do that. It's just a matter of working out the process.
In your case, I would do the following steps:
Order the data by users, then by date so everything is nicely together
Loop through the data and each time, check that the current user is the same as the last one. if it's not, create a new array key
split the date into the parts you want
check the user array for the key relating to year for that user. If the year exists, search for the month. If the month exists, add 1 to the total for that month. If the year and/or month don't exist, create the keys and set the total to be 1 for that month
Once the records have been processed, you should have the data in the format you need.

Codeigniter calendar multiple events on same day

I am trying to add multiple events to codeigniter calendar. I have found solution for that already. The problem I am facing is that, for multiple events on same day I want array like this
$data = array(
1 => 'class1',
3 => array('class2', 'class3'),
4 => 'class4'
);
Here is my model function and mysql query
public function getClasses($year,$month)
{
$this->db->like('date_from', $year."-".$month, 'after');
$query = $this->db->get('classes');
$data = array();
foreach($query->result() as $row)
{
$data[(int)substr($row->date_from, 8, 2)] = $row->class_name;
}
return $data;
}
date_from is in this format 2015-02-25
Right now the function make single array for example
$events = array(
1 => 'class1',
4 => 'class4'
);
But I want it to make nested array. How this can be solved?

MySQL IN return only the single record

Hi i am using CakePHP version 2.x i have faced in a problem. Please check my code
points table
id point
-----------
1 5
2 6
3 1
4 5
Code:
$myPoint = $this->find("first",array('conditions'=>array('user_id'=>CakeSession::read('Auth.User.id')),'fields'=>array('point','active_column')));
echo $myPointList = $myPoint['User_point']['active_column'];
Output: 2,3
$Point = ClassRegistry::init('Point');
$Point->virtualFields['point'] = 'SUM(Point.point)';
$getPoints = $Point->find('first', array(
'conditions'=>array(
'Point.id'=>array($myPointList)),'fields' => array(
'point')));
echo $getPoints['Point']['point']; exit;
In above output the 2 and 3 sum of point is 6+1=7
But i am getting only 6 why?
Edit :
$myPointList is dynamic if i use static there the result is showing perfect. Please check below code
Code:
$getPoints = $this->Point->find('first', array(
'conditions'=>array(
'Point.id'=>array(2,3)),'fields' => array(
'point')));
the problem is that $myPointList is a string. Try this code
$getPoints = $Point->find(
'all',
array(
'conditions'=>array(
'Point.id IN (?)'=> $myPointList,
)
'fields' => array (
'point'
)
)
);
or you can tranform $myPointList into an array using explode
$myPointList = explode(',', $myPointList);
$getPoints = $Point->find(
'all',
array(
'conditions'=>array(
'Point.id'=> $myPointList,
)
'fields' => array (
'point'
)
)
);
you can use find('first') but it's better if you use find('all'). Using find('first') just appends a 'LIMIT 1' to the generated query. This not affects your result as the LIMIT is applied after the SUM. But it's unnecessary so I think you can avoid using it
edit: after reading the comments from #AD7six
you'd better use field() instead of find(). So your code becomes
$getPoints = $Point->field(
'SUM(Point.point)',
array(
'Point.id IN (?)'=> $myPointList
)
);
Or
$myPointList = explode(',', $myPointList);
$getPoints = $Point->field(
'SUM(Point.point)',
array(
'Point.id'=> $myPointList
)
);
CakePhp IN allow array() but your data returns as a normal text like 2,3 I have converted it string to array using explode() function.
$arrryMypoint=explode(",",$myPointList); Please update in your code and let me know its working or not?
Please use this code:
$myPoint = $this->find("first",array('conditions'=>array('user_id'=>CakeSession::read('Auth.User.id')),'fields'=>array('point','active_column')));
$myPointList = $myPoint['User_point']['active_column'];
$arrryMypoint=explode(",",$myPointList);
$Point = ClassRegistry::init('Point');
$Point->virtualFields['point'] = 'SUM(Point.point)';
$getPoints = $Point->find('first', array(
'conditions'=>array(
'Point.id'=>$arrryMypoint),'fields' => array(
'point')));
echo $getPoints['Point']['point']; exit;
If you use first then it will return only first record , in your case the output would be that of id 2 only, so use all instaed of first
$myPoint = $this->find("all",array('conditions'=>array('user_id'=>CakeSession::read('Auth.User.id')),'fields'=>array('point','active_column')));
echo $myPointList = $myPoint['User_point']['active_column'];
$getPoints = $Point->find('all', array(
'conditions'=>array(
'Point.id'=>array($myPointList)),
'fields' => array('SUM(Point.point)')
)
);

Categories