Codeigniter array issue - arrays

I'm trying to loop through an array and insert my values into the database. My table looks like this:
hours_day
hours_open
hours_close
My form enables the user to select a day, an opening time and a closing time. There is a plus button which adds another day below it, so the user can choose whichever days they wish. This means that my select box names are arrays, i.e. hours_day[]
My Model looks like this:
$hours = array(
'hours_day' => $this->input->post('venue_hours_day'),
'hours_opening' => $this->input->post('venue_hours_open'),
'hours_closing' => $this->input->post('venue_hours_close'),
);
So I have an array ($hours) with arrays inside of it (hours_day, hours_opening, hours_closing). How do I loop through this an add it to my database?

You can use :
$post_day = $this->input->post('venue_hours_day');
$post_opening = $this->input->post('venue_hours_open');
$post_closing = $this->input->post('venue_hours_closing');
$count = count($post_day);
$results = array();
for ($i = 0; $i < $count; $i++)
{
$results []= array(
'hours_day' => $post_day[$i],
'hours_opening' => $post_opening[$i],
'hours_closing' => $post_closing[$i]
);
}
$this->db->insert_batch('your_table', $results);

Related

save data in separate array in each iteration

$this->layout='defaultall';
$id = $this->Auth->user('idUser');
$data= $this->Contact->find('all',array(
'conditions' => array('Contact.User_id' => $id)));
$this->set('contacts',$data);
$this->loadModel('Calllog');
/* for($i=1; $i < 2; $i++)
{
$mobile =$data[$i]['Contact']["mobileNo"];
$work =$data[$i]['Contact']["workNo"];
$home =$data[$i]['Contact']["homeNo"];*/
for($data as $datas){
$mobile= $datas['Contact']['mobileNo'];
$home= $datas['Contact']['homeNo'];
$work= $datas['Contact']['workNo'];
$recent=$this->Calllog->find('all',
array('order'=>'Calllog.idCallLog DESC',
'limit' => 1,
'conditions' => array('Calllog.mobileNo' => array($mobile,$work,$home ),
'Calllog.User_id' => $id
)));
//here array want to declare
$this->set('a',$recent);
//here i want to declare an another array which saves the data of every iteration..because i dont want override the data
sorry i am week in arrays.. and do tell me how can i then print the array ...if i want to display the 1st iteration result in my view page
If you just want to add new element to the array without deleting its content you can do that just like that:
$recent[] = 'new_string1';
or if you have more elements:
array_push($recent, 'new_string1', 'new_string2');
But in the future, please read manual: http://php.net/manual/en/function.array-push.php

Why this code add only a single data from an array into a menu table

I am able to obtain the $data array from a form and I can generate data for each item... But during the binding and storing with jTable object it saves only the latest item why... I am using native JTableMenu class to bind and save by using my own class which is extended by native one. Early trials I used database object to save items with sql syntax but some columns of table remains empty lft and rgt to fill them I used table object but it gives this issue.
The whole code is following:
function addcumulative($data){
$db = JFactory::getDBO();
$component = & JComponentHelper::getComponent('com_dratransport');
$menus = array();
$query = array();
$countries = DraTransportHelperArrays::countries();
$cities = DraTransportHelperArrays::cities();
$title = array();
$alias = array();
$path = array();
$link = array();
if(empty($data['parent_id']) && $data['parent_id'] == 0){
$data['parent_id'] = 1;
}else{
$parent_id = explode('.',$data['parent_id']);
$data['parent_id'] = $parent_id[1];
}
if(!empty($data['locationQuery'])){ //actually this part will be used
$loc = ($data['locationQuery'] == 'countries') ? $countries : $cities['Turkey'] ;
foreach($loc as $k => $c){
$query[0] = $data['general'];
foreach($data as $key => $dat){
if(!empty($dat) && strpos($key,'Query') !== false){
$v = explode('Q',$key);
if($v[0] !== 'location'){
$query[] = '&'.$v[0].'='.$dat;
}else{
$query[] = '&'.$dat.'='.$k;
}
}
}
$title[] = $data['viewQuery'].'-'.$k;
$alias[] = $data['viewQuery'].'-'.$k;
$path[] = $data['viewQuery'].'-'.$k;
$link[] = implode('',$query);
$query = array();
}
}else{
$query[0] = $data['general'];
foreach($data as $key => $dat){
if(!empty($dat) && strpos($key,'Query') !== false){
$v = explode('Q',$key);
$query[] = '&'.$v[0].'='.$dat;
}
}
$link[] = implode('',$query);
}
foreach($link as $n => $l){
$menus[] = array(
'menutype' => $data['menutype'],
'title' => $title[$n],
'alias' => $alias[$n],
'path' => $path[$n],
'link' => $link[$n],
'type' => 'component',
'published' => 1,
'parent_id' => $data['parent_id'],
'level' => 1,
'component_id' => $component->id,
'access' => $data['access'],
'params' => $data['params'],
'language' => '*'
);
}
$count = $data['count'] == 0 ? count($loc) : $data['count'];
foreach($menus as $menu){
// Bind the data.
$table = $this->getTable();
$table->bind($menu);
$table->store();
}
}
Yes you are totally right. Let say $countries=array('England','France','Germany'); then I wrote my code in model to generate links in #__menu table. So I write
foreach($countries as $country){
$link='index.php&option=com_mycomponent&view=members&type=1&countries='.$country;
$table->bind();
$table->save();
}
I am generating links like this, view and the type values in query comes from the form submitted to make parmaters same for all menus except countries;
and I assign all parametes to manu item and menu items to an array as array item...
to save database the table comes with nested.
$menus->$each menu as $menus array item->menu item parameters
while the table is first created in above code code just adds the last menu item but if I take it insede the foreach it adds all of them but parent_id and level parameters assigned to 0 bye the native code altought I set them as 1

Drupal 7 theme(''pager') -> table get's rendered but without Pager?

I have a table with data from the database, I would like it to have a Pager, I have all the code from an example (of buildamodule.com) among other sites, and my table get's rendered, but it doesn't generate a pager, although I have more rows then the limit:
the function:
function get_loyaltycodes(){
$headers = array(
array(
'data' => t('Code')
),
array(
'data' => t('Info')
),
array(
'data' => t('Points')
),
array(
'data' => t('Consumed by')
),
);
$limit = variable_get('codes_per_page',5);
$query = db_select('loyalty_codes','lc');
$query -> fields('lc',array('code','info','points','uid'))
-> orderBy('lc.info','ASC')
-> extend('PagerDefault')
-> limit($limit);
//to see all codes for a certain amount of points, just append the number of points to the URL
$arg = arg(2);
if($arg != '' && is_numeric($arg))
{
$query->condition('points', $arg);
}
// Fetch the result set.
$result = $query->execute();
$rows = array();
// Loop through each item and add to the $rows array.
foreach ($result as $row) {
$rows[] = array(
$row->code,
$row->info,
$row->points,
$row->uid,
);
}
// Format output.
$output = theme('table', array('header' => $headers, 'rows' => $rows)) . theme('pager');
return $output;
the $limit variable is set to 5 in the settings form, and it is 5 in the database too.
Anybody who has any idea in why the pager is not showing? perhaps something in the formatting off the output?
Help is very much appreciated!
apparently I can't log in right know because I'm behind a firewall, anyway I seem to have fixed it, stupid mistake though:
the ‘->extend(‘PagerDefault’) extension in the query had to be the first function in the daisy chain. If not there is no error but the function seems to not be called.
$query = db_select('loyalty_codes','lc')
->extend('PagerDefault')
-> fields('lc',array('code','info','points','uid'))
-> orderBy('lc.info','ASC')
-> limit(5);//$limit);

How to only display search results when needed in cakephp?

I have the following situation where I want to only display the search results when user search for something. Currrently, as I access my search page, all the search results is being displayed and if user search for a particular thing, it displays that accordingly. The following is the code in my search controller. I added a pagination for it to paginate.
function simple_search() {
$this->User->recursive = 1;
$this->Passion->recursive = 1;
$this->User->unBindModel(array('hasMany' => array('Topic','Post')),false);
$conditions = array();
$options;
$or_conditions = array();
$final_conditions = array();
$search_fields = array('User.firstName', 'User.lastName', 'User.email', 'User.displayName'); //fields to search 'Video.tags','Video.desc'
$this->layout = "mainLayout";
$value='';
if(!empty($this->params["url"]["value"])){
$value = $this->params["url"]["value"];
}
$searches = explode(" ", $value);
foreach ($search_fields as $f) {
array_push($conditions, array("$f Like" => "$value%"));
for ($i = 0; $i < count($searches); $i++) {
if ($searches[$i] != "") {
array_push($conditions, array("$f Like" => "$searches[$i]%"));
}
}
array_push($or_conditions, array('OR' => $conditions));
$conditions = array();
}
$final_conditions = array('OR' => $or_conditions);
$users = $this->User->find('all', $final_conditions);
$this->paginate = array(
'conditions' => $final_conditions,
'limit' => 10
);
$users = $this->paginate('User');
$this->set('search_fields', $users);
}
Why are you doing the find('all')? A few lines later paginate() overrides the result.
empty($this->params['url']['value'] check this and set your results to the view only in the case its not empty.
Follow the coding standard for CakePHP and use camelCased variable names instead of underscores. http://book.cakephp.org/2.0/en/contributing/cakephp-coding-conventions.html
Also you might want to take a look at this.
https://github.com/CakeDC/search
And at this (showing a custum find using search plugin)
https://github.com/CakeDC/users/blob/master/controllers/users_controller.php#L316
https://github.com/CakeDC/users/blob/master/models/user.php#L557

How to add another view with customized "find" in CakePHP?

I currently have index, view, add and edit from my tickets/views and am planning to add another view called current. I want to display only the "Resolved" tickets on that view but have no idea how to do it. I've been trying to figure this out for the past couple of days with no luck. Where should I put the "find" code and what should I include on my tickets/current view code? Here's what I have tried so far:
/controllers/tickets_controller
function current() {
$current = $this->set('tickets', $this->Ticket->find('all', array(
'conditions' => array('Ticket.status' => 'Resolved'),
'order' => array('Ticket.created' => 'desc')
)));
$this->set('tickets', $this->paginate());
}
/views/tickets/current.ctp
<?php
$i = 0;
foreach ($tickets as $ticket):
$class = null;
if ($i++ % 2 == 0) {
$class = ' class="altrow"';
}
?>
This code displays the same as /views/tickets/index.ctp (with all the records from the table).
Thanks,
Lyman
You were almost there. $this->set('foo') in Cake is one way you can pass variables to the view.
What the code below does is set a variable called current the return value of the find method which has a custom condition, which can be accessed from the view. (It's an array in this case; but you can set anything)
You don't need the paginate() here unless you plan to use pagination in this view.
So something like this should do the trick ($curr is a bad variable name but I wasn't feeling inventive. (resolved_tickets would make more sense (why current?))
//controllers/tickets_controller
function current() {
$this->set('current', $this->Ticket->find('all',
array('conditions' => array('Ticket.status' => 'Resolved'),
'order' => array('Ticket.created' => 'desc')
)));
}
/views/tickets/current.ctp
<?php
$i = 0;
// adjust the variable in the foreach
foreach ($current as $curr):
$class = null;
if ($i++ % 2 == 0) {
$class = ' class="altrow"';
}
echo $curr['Ticket']['id']; // example
?>

Resources