How to insert value of my checkbox to different column in database codeigniter - codeigniter

This should be like this
ID|access1|access2|access3|
and values:
1|1|0|1
//myController
$basic_data = array();
$select_access1 = $_POST("select_access1");
$select_access2 = $_POST("select_access2");
$select_access3 = $_POST("select_access3");
$select_access4 = $_POST("select_access4");
$select_access5 = $_POST("select_access5");
$basic_data[] = array('accs_trans_sec'=>$select_access1,'accs_acctng_sec'=>$select_access2, 'accs_admin_sec'=>$select_access3,'accs_dashboard_sec'=> $select_access4, 'accs_reports_sec'=>$select_access5);
$this->RoleModel->saveRole($basic_data);
//myModel
public function saveRole($basic_data)
{
foreach($basic_data as $value) {
$this->db->insert('roles_global_access', $basic_data);
}}

You can set that data to array just like this:
$data = array(
'column1' => 'My Value 1',
'column2' => 'My Value 2',
'column3' => 'My Value 3'
);
$this->db->insert("table_name", $data);

Let's assume that you are getting the values of your checkbox based on your $_POST variables.
Since you've declared $basic_data as array() no need to cast it as $basic_data[].
So on your controller it should be like this:
$basic_data = array(
'accs_trans_sec'=>$select_access1,
'accs_acctng_sec'=>$select_access2,
'accs_admin_sec'=>$select_access3,
'accs_dashboard_sec'=> $select_access4,
'accs_reports_sec'=>$select_access5
);
And your model there's no need to use loop since you are inserting Object data it should look like this:
public function saveRole($basic_data)
{
$this->db->insert('roles_global_access', $basic_data);
return ($this->db->affected_rows() != 1) ? false : true;
}
so basically, if the model returns true then it successfully inserted the data.
To check if data is inserted successfully:
$result = $this->RoleModel->saveRole($basic_data);
if($result == true){
echo ("Successfully inserted!");
}else{
echo ("Problem!");
}

First, you are not getting post data in the correct way. With $_POST have to use square brackets [].
Second, Don't use foreach loop in the model
Get data in the controller like this
$basic_data = array(
'accs_trans_sec' => $_POST['select_access1'],
'accs_acctng_sec' => $_POST['select_access2'],
'accs_admin_sec' => $_POST['select_access3'],
'accs_dashboard_sec' => $_POST['select_access4'],
'accs_reports_sec' => $_POST['select_access5']
);
$this->RoleModel->saveRole($basic_data);
Model
public function saveRole($basic_data){
return $this->db->insert('roles_global_access', $basic_data);
}

You should try this.
Controller:
$this->RoleModel->saveRole($_POST);
Model:
public function saveRole($basic_data){
extract($basic_data);
$dataset = array(
'accs_trans_sec' => $basic_data['select_access1'],
'accs_acctng_sec' => $basic_data['select_access2'],
'accs_admin_sec' => $basic_data['select_access3'],
'accs_dashboard_sec' => $basic_data['select_access4'],
'accs_reports_sec' => $basic_data['select_access5']
);
$this->db->insert('roles_global_access', $dataset);
}

Related

Laravel : array_push not working in collection->each() iterator

I have grouped collection and I iterate it using each() function.Inside the each function I want to add element to some array.But it is not working.Any idea?
$dataSet1 = [];
$appointments = [
['department' => 'finance', 'product' => 'Chair'],
['department' => 'marketing', 'product' => 'Bookcase'],
['department' => 'finance', 'product' => 'Desk'],
];
$groupData = collect($appointments)->groupBy('department');
$groupData->each(function ($item, $key) {
Log::info($key); //Show correct output in log
array_push($dataSet1, $key); //ERROR
array_push($dataSet1, 'A');//ERROR
});
Laravel version : 8.35.1
You need to pass the array to the function with use:
$groupData->each(function ($item, $key) use (&$dataSet1) {
Log::info($key); //Show correct output in log
array_push($dataSet1, $key); //ERROR
array_push($dataSet1, 'A');//ERROR
});
Pass-by-reference (&) is needed as long as $dataSet1 is not an object instance.

Difference between Redirect::to() and View::make()

I have a blade form that posts to Controller, the controller then will redirect to the same URL after performing some operations.
Before redirecting to the user, two variables will be passed. My problem is that when using Redirect::to() only the ->with('item_list',$item_list) is made available for the view, while ->with('added_items',$added_items) when using the $added_items variable in the view gives me the error:
ErrorException
Undefined variable: added_items (View: /var/www/mw/app/views/delivery->
requests/create.blade.php)
Controller
if (Input::has('addItem'))
{
if (Session::has('added-items'))
{
$id = Input::get('item_id');
$new_item = Item::find($id);
Session::push('added-items', [
'item_id' => $id,
'item_name' => $new_item->item_name,
'item_quantity' => Input::get('item_quantity')
]);
$array = Session::get('added-items');
//move outside foreach loop because we don't want to reset it
$total = array();
foreach ($array as $key => $value)
{
$id = $value['item_id'];
$quantity = $value['item_quantity'];
if (!isset($total[$id]))
{
$total[$id] = 0;
}
$total[$id] += $quantity;
}
$items = array();
foreach($total as $item_id => $item_quantity)
{
$new_item = Item::find($item_id);
$items[] = array(
'item_id' => $item_id,
'item_name' => $new_item->item_name,
'item_quantity' => $item_quantity
);
}
Session::put('added-items', $items);
}
else
{
$id = Input::get('item_id');
$new_item = Item::find($id);
Session::put('added-items', [
0 => [
'item_id' => $id,
'item_name' => $new_item->item_name,
'item_quantity' => Input::get('item_quantity')
]
]);
}
// pass the items again to the page
$item_list = Item::lists('item_name', 'id');
$added_items = Session::get('added-items');
return View::make('delivery-requests/create')
->with('added_items',$added_items)
->with('item_list', $item_list);
}
The reason I used Redirect::to() is that it maintains the same URL which is /delivery-requests/create
But when I use View::make() I can access the $added_items variable just fine, but the URL now becomes /delivery-requests , even if I explicitly put it like this:
return View::make('delivery-requests/create')
->with('added_items',$added_items)
->with('item_list', $item_list);
My question is why can't Redirect::to() read the $added_items variable on the view
Instead of redirecting to the route, return the method which is at the end of that route with any additional variables you need.
return $this->create()->with('added_items', $added_items)->with('item_list', $item_list) where create() is the method which is being used on the route delivery-requests/create.
Redirect is probably what you are actually after then,
Redirect::to()->with('item_list', $item_list);

Use Array Data in CodeIgniter Model as SQL?

In my controller, I am passing data to the model using the following code:
$data = array(
'gid' => $this->input->post('gid'),
'name' => $this->input->post('name'),
'pic' => $this->input->post('pic'),
'link' => $this->input->post('link')
);
var_dump($data);
$this->Login_model->insert_entry($data);
In my model, what I want to do is use the gid value as part of an SQL statement, like so:
$get_gid = $this->db->query('SELECT * FROM users WHERE gid = $gid');
Obviously this doesn't work, so I'm just wondering how I get the gid from $data and use it in my SQL statement?
Tested using
$get_gid = $this->db->where('gid', $data['gid'])->get('users');
print_r($get_gid);
However output is:
CI_DB_mysql_result Object ( [conn_id] => Resource id #30 [result_id]
=> Resource id #33 [result_array] => Array ( ) [result_object] => Array ( ) [custom_result_object] => Array ( ) [current_row] => 0
[num_rows] => 0 [row_data] => )
Did you try gid = $data['gid']
I assume that yours model method looks like this:
insert_entry($data)
{
here active record or query...
}
If yes try to display query to see if $data['gid'] is visible there
You can try it by
$this->db->get_compiled_select();
Or after query runs
$this->db->last_query();
Try this way:
$data = array(
'gid' => $this->input->post('gid'),
'name' => $this->input->post('name'),
'pic' => $this->input->post('pic'),
'link' => $this->input->post('link')
);
$gid = $data['gid'];
$this->db->where('gid',$gid);
$this->db->from('users');
$query = $this->db->get();
if($query)
{
//you can return query or you can do other operations here like insert the array data
//$this->db->insert('yourtable',$data);
return $query;
}
else
{
return FALSE;
}
You can try:
$get_gid = $this->db->query('SELECT * FROM users WHERE gid = '.$data['gid'].');
You just Forget after query $query->result().

codeigniter get last insert id from model to use as redirect parameter

I need to get the insert ID to be used in my controller, the problem is my model function has several data arrays, and I need the insert ID of the 1st array. therefor if I try to get the insert ID on my controller obviously its grabbing the 2nd insert ID and not the 1st.
I'm not sure this makes sense but here is an example:
Model
public function add() {
$data = array(
'name' => $_POST['companyName']
,'type' => $_POST['companyType']
,'active' => '1');
$this->db->insert('company', $data);
$cid = $this->db->insert_id();
$data2 = array(
'cid' => $cid
,'name' => $_POST['locationName']
,'address' => $_POST['locationAddress']);
$this->db->insert('locations', $data2);
}
This is working fine...However after this runs, on my controller the redirect is getting the data2 last insert which makes my redirect wrong.
Controller
public function add() {
if (isset($_POST["add"]))
{
$this->Company_model->add();
$id = $this->db->insert_id();
redirect('company/view/'.$cid);
}
$data['states'] = $this->Company_model->
}
Any help would be greatful!
You were very close. Instead of repeating $id = $this->db->insert_id(); in your controller, you can return the $cid from your models method.
Model
public function add() {
$data = array(
'name' => $_POST['companyName']
,'type' => $_POST['companyType']
,'active' => '1');
$this->db->insert('company', $data);
$cid = $this->db->insert_id();
$data2 = array(
'cid' => $cid
,'name' => $_POST['locationName']
,'address' => $_POST['locationAddress']);
$this->db->insert('locations', $data2);
// This returns your first inserts id
return $cid;
}
Controller
public function add() {
if (isset($_POST["add"]))
{
$id = $this->Company_model->add();
redirect('company/view/'.$id);
}
...

CakePHP model validation with array

I want to use CakePHP's core validation for lists in my model:
var $validate = array(
'selectBox' => array(
'allowedChoice' => array(
'rule' => array('inList', $listToCheck),
'message' => 'Enter something in listToCheck.'
)
)
);
However, the $listToCheck array is the same array that's used in the view, to populate a selectbox. Where do I put this function?
public function getList() {
return array('hi'=>'Hello','bi'=>'Goodbye','si'=>'Salutations');
}
Already in my controller, in one of the actions I'm setting it for the view, like:
public function actionForForm() {
$options = $this->getList();
$this->set('options', $options);
}
So, I don't want to have to copy the getList() function...where can I put it so the Model can call it to populate its $listToCheck array?
Thanks for your help.
Considering that it's data, you should store the list of valid choices in the model.
class MyModel extends AppModel {
var $fieldAbcChoices = array('a' => 'The A', 'b' => 'The B', 'c' => 'The C');
}
You can get that variable in the Controller simply like this:
$this->set('fieldAbcs', $this->MyModel->fieldAbcChoices);
Unfortunately you can't simply use that variable in the rule declaration for the inList rule, since rules are declared as instance variables and those can only be initialized statically (no variables allowed). The best way around that is to set the variable in the Constructor:
var $validate = array(
'fieldAbc' => array(
'allowedChoice' => array(
'rule' => array('inList', array()),
'message' => 'Enter something in listToCheck.'
)
)
);
function __construct($id = false, $table = null, $ds = null) {
parent::__construct($id, $table, $ds);
$this->validate['fieldAbc']['allowedChoice']['rule'][1] = array_keys($this->fieldAbcChoices);
}
If you're not comfortable overriding the Constructor, you could also do this in a beforeValidate() callback.
Also note that you shouldn't name your field 'selectBox'. :)

Resources