codeigniter Pass array from view to controller - php

View:
user_data coming from the controller (Database middleware values)
<?php
$ID['IDS'] = array_column($user_data, 'ID');
print_r($ID);
// print_r($ID)=Array( [IDS] => Array([0] => 0 [1] => ABCD [2] => EFG ) )?>
Controller
$postData = $this->input->post();
$payment_code=$postData['IDS'];
$payment_code=$ID;
$postData = $this->input->post();
echo "<b>Name :</b> ".$postData['IDS']."<br/>";
$this->load->view('Demo/code_Send_data', ['code_key'=>$payment_code]);
[ Questions ]
can not see value in code_Send_data view
how to pass array value from view to controller
Is my <?php echo form_open('login/send_validated_Code_To_final',$ID['IDS']); ?> syntax correct ??

If you want to send additional hidden input data from the view to the controller, add a third parameter containing the data array (the second parameter is for the attribute, you can leave it empty) :
$ID['IDS'] = array_column($user_data, 'ID');
<?php echo form_open('login/send_validated_Code_To_final', '', $ID); ?>
Refs : Form Helper Documentation

Related

Problems Trying Insert Data in Database using $this->input->post() - Codeigniter

Im trying use "$this->input->post();" of Codeigniter to do not need specify each field in my form. But im getting troubles when try insert into Database.
Look my controller:
public function cadastrar(){
$var = $this->input->post(null, TRUE);
$this->load->model('m_clientes');
$this->m_clientes->inserir($var);
}
My controller is simplified here because i know how to handle database in codeigniter.
The result of this post was:
Array ( [nome] => Raphael [sobrenome] => Schubert [cpf] => 893.528.432-89 [rg] => 4529875231908472 [telefone] => (53) 2980-5792 [celular] => (53) 9 2180-7529 [rua] => Israel de Almeida [numero] => 859 [cep] => 88.312-000 [bairro] => São Vicente [cidade] => ITAJAÍ [estado] => Santa Catarina [email] => rfswdp#gmail.com [tipo] => pf [cnpj] => 34.827.481/2834-78 [inscricaoestadual] => 34120489032814930128 [razaosocial] => Teste [nomefantasia] => Disney [dataaberturaempresa] => 10/21/15 [proprietario] => Marcos Aurelio )
I normaly use this way to insert:
$data = array(
'user_name' => $this->input->post('user_name',TRUE);
'user_phone' => $this->input->post('user_phone',TRUE);
'user_role' => $this->input->post('user_role',TRUE);
);
$this->name_of_model->inserir($data);
And works...
But i was trying to use just $this->input->post(); to get all fields from form. Because my actualy application will have hundreds of fields and i was trying to do not write each line.
So my model actually was:
public function inserir($var){
if($var!=NULL):
print_r($var);
$this->db->insert('tb_usuarios',$var);
endif;
}
But i`m getting and error saying:
Message: Undefined property: Clientes::$db
and
Message: Call to a member function insert() on null
My table name is: "tb_usuarios"
I changed all fields in database to accept NULL to see if i`m get some field name wrong... but not work...
Any tips??
There is no need to catch the POST var inside $var. You can see POST variable inside the model very well. So all you need to do in the controller is:
public function cadastrar(){
$this->load->model('m_clientes');
$this->m_clientes->inserir();
}
,and inside your model:
public function inserir(){
if( count($this->input->post()) > 0):
$this->db->insert('tb_usuarios',$this->input->post());
endif;
}
The fields names in your form must correspond to the column names inside your table.
The message Message: Call to a member function insert() on null means you forgot to load the database library, just like remiheens said.
But my advice is, to use form validation for your fields, so you may be sure all necessary fields are completed using the required data format for each one of them. Although this may require allot of coding, there is no other safe way from errors on database operations. You cannot trust the user to insert the data correctly, that's why you need form validation.
In here $var = $this->input->post(null, TRUE); you use null. null is not valid input name. name = ''
and this will works $this->input->post('user_name',TRUE);
cz of it has input tag name (name = 'user_name').
We use ,TRUE) next to input post field to allows XSS Protection
$var = $this->input->post(null, TRUE); Is Wrong
while you trying this, it shows
Message: Undefined property: Clientes::$db and Message: Call to a member function insert() on null.
will not work
public function cadastrar(){
$var = $this->input->post(null, TRUE);//will never give valid response
$this->load->model('m_clientes');
$this->m_clientes->inserir($var);
}
Works well
public function cadastrar(){
$this->load->model('m_clientes');
$data = array(
'user_name' => $this->input->post('user_name',TRUE);
'user_phone' => $this->input->post('user_phone',TRUE);
'user_role' => $this->input->post('user_role',TRUE);
);
$this->name_of_model->inserir($data);
$this->load->model('m_clientes');
}
This is because your database isn't loaded into codeigniter instance. ($this->db)
Just try to autoload "database" library (config/autoload.php) or load/connect your database in your model with :
$this->load->database();
Don't forget to edit your config/database.php ;)
I handle hundreds of fields everytime but I also validate basically each one. I always do this:
$customer['name'] = $this->input->post('customer_name');
$customer['age'] = $this->input->post('customer_age');
$customer['country'] = $this->input->post('customer_country');
$customer['city'] = $this->input->post('customer_city');
// validations
if(isAgeValid($customer['age']) == FALSE)
{
echo 'Hold on, your age...hmm check it out!';
return;
}
$this->customers_model->add($customer);
The function that handles the insertion only has this:
public function add($data)
{
$data = $this->security->xss_clean($data);
$this->db->insert('customers', $data);
return $this->db->insert_id();
}
Pretty clean and simple. Now, if you don't want to validate the fields or just want to validate some of them and want to insert the others without validation this is what I purpose based on the previous code:
// validations..
if(isAgeValid());
$customer = array();
foreach($_POST as $key => $value)
$customer[$key] = $value;
$this->customers_model->add($customer);
$data = array(
'user_name' => $this->input->post('user_name');
'user_phone' => $this->input->post('user_phone');
'user_role' => $this->input->post('user_role');
);
$this->load->model('name_of_model');
$this->name_of_model->inserir($data);
Model:
public function inserir($data)
{
$this->db->insert('***', $data);
if ($this->db->affected_rows() > 0) {
return true;
}
}

Detect how many array exist?

I am using CodeIgniter framework. I am sending an array to my view, but I could not get the array in my view.
This is my controller code:
public function edit($id)
{
$record = $this->Start_model->get_entry($id);//receiving array from model
$this->load->view('edit',$record);//send array to my view
}
This is my array on controller that I send:
Array
(
[0] => Array
( [id] => 1 [name] => Hamza [age] => 20 [address] => audit and account [phone] => 03000000000 )
)
But when I call this array view I get this error:
Undefined variable: record
This is how I am getting my array in view:
<?php
echo '<pre>';
print_r($record);
echo '</pre>';
?>
Now I know I am sending an array to my view but I want to know If there is array in my view or not. I can get record through another method but I think it is not a good practice. So anyone can help me how I can detect if there is an array in my view?
In your controller, send a parent array instead:
public function edit($id)
{
$data = array();
$data['record'] = $this->Start_model->get_entry($id); // provided this is not empty
$this->load->view('edit', $data);
}
Then in your view:
foreach($record[0] as $key => $value) {
echo $value['id'];
// the rest blah blah
}
Codeigniter extracts the array passed to a view, creating variables based on the keys of the array. To work as you want, pass an array with a key or record and a value of your array:
public function edit($id)
{
$data = array('record' => $this->Start_model->get_entry($id));
$this->load->view('edit',$data);//send array to my view
}
Then this will work in your view:
<?php
echo '<pre>';
print_r($record);
echo '</pre>';
?>
The way you are currently sending the data, it will be extracted into individual variables for each element in the array, however as your array is numerically indexed, and php variable name rules prevent numeric variable names, you cannot access the data.

Yii: How to get list of checkboxes?

I have a table called Table, it has id and name as attributes.
For each entry in Table, I would like to generate a checkbox.
How can I do this?
I am using the Yii-Boostrap plugin, which I'm expecting I would need use something like this:
foreach(...)
echo $form->checkBoxRow($model, 'name');
Which I got from the Yii-Bootstrap Documentation.
Try this simple one
And in this for precheck to work just pass the array as second parameter
as shown below
<?$select=array('2','3');?>
<?php echo CHtml::checkBoxList(
'TableValues',
'$select',//you can pass the array here which you want to be pre checked
CHtml::listData(Table::model()->findAll(),'id','name'),
array('checkAll'=>'Select all tasks', 'checkAllLast'=>true)
); ?>
And you can get the selected checkbox values in the controller using
print_r($_POST['TableValues']);
UPDATED
For this the precheck to work u have to assign the array to the model attribute as shown below
<?php $model->modelAttributename=array('3','5')//respective checked values as of yours
<?php echo $form->checkBoxList(
$model,
'modelAttributename',
CHtml::listData(Table::model()->findAll(),'id','name'),
array('checkAll'=>'Select all tasks', 'checkAllLast'=>true)
); ?>
You should see your result array form sql query and see how to access any string you want from result array and then you create array of string that contain list of name.
e.g. your result query is $result["name"] = array("a","b","c");
<?php /** #var BootActiveForm $form */
$form = $this->beginWidget('bootstrap.widgets.TbActiveForm', array(
'id'=>'horizontalForm',
'type'=>'horizontal',
));
?>
<fieldset>
<legend>Legend</legend>
<?php
$result["name"] = array("a","b","c");
echo $form->checkBoxListRow($model, 'checkboxes', $result["name"]);
?>
</fieldset>
Check this example:
Book Model:
'authors' => array(self::MANY_MANY, 'Author', 'authorbook(book_id,author_id)'),
Author Model:
'books' => array(self::MANY_MANY, 'Book', 'authorbook(author_id, book_id)'),
Checkbox List in form:
$books = CHtml::listData(Book::model()->findAll(), 'id', 'name');
$selected_keys = array_keys(CHtml::listData( $model->books, 'id' , 'id'));
echo CHtml::checkBoxList('Author[books][]', $selected_keys, $books);

CodeIgniter Getting the result of a query as a text input value

I wrote a small piece to get a value from a database table according to the input user provides. Quickly here are the events:
User inputs number to an input and submit form
That data are supposed to call the controller, and then the controller have to match and grab relevant data from the database table, and pass it to the controller again.
Then the controller must pass it to the view, where another text input (readonly) picks up the data as the value.
But what I received was an error:
Message: Undefined variable: due_amount
Filename: main/new_payment.php
Line Number: 148
Line number 148 in new_payment.php is
);
in the View.
This is my Model:
function get_by_room_number($room_data) {
$this->db->select('due_amount');
$query = $this->db->get_where('rooms', array('room_number' => $room_data), 1);
if($query->num_rows()>0) {
foreach ($query->result() as $row) {
return $row->due_amount;
}
}
This is the Controller:
function search_by_number() {
$room_data = $this->input->post('room_number');
$due_amount = $this->payments_model->get_by_room_number($room_data);
$this->index();
}
This is the View: (new_payment.php)
<?php echo form_open('payments/search_by_number'); ?>
<?php $data = array(
'name' => 'total_amount',
'id' => 'appendedPrependedInput',
'class' => 'span2',
'value' => $due_amount
); // Line Number 148
echo form_input($data);
?>
<?php echo form_close(); ?>
Try like
$data['due_amount'] = $this->payments_model->get_by_room_number($room_data);
and try to sent it to view like
$this->load->view('view_file',$data);
and at your view file echo it like
echo $due_amount;
assuming that $data is the array that you are passing to your view from your controller function.You cont pass a variable from controller to view.You need to pass it through an array data and then you can get the variable with that variable name
You should assign due_amount to $data variable and pass it to view. Like this:
$data['room_data'] = $this->input->post('room_number');
$data['due_amount'] = $this->payments_model->get_by_room_number($data['room_data']);
$this->load->view('my_view', $data);
Then in view you could do:
print_r($room_data);
print_r($due_amount);
CodeIgniter User Guide might help you understand it better.

How to access array fields in codeigniter?

I'm trying to pass two arrays ($a_1 and $a_2) from my controller to my view like so:
$this->load->view('confirm_data_v', $a_1, $a_2);
In my view I want to print the value of one of them doing this:
<p><?php echo $name ?></p>
<p><?php echo $mail ?></p>
when I print each array I get this:
Array
(
[name] => jon
)
Array
(
[mail] => blabla#server.com
)
$name is a field inside $a_1 and $mail is a field inside $a_2, but it seems like the view doesn't know where these fields are, I mean, it doesn't know in wich array is $name and $mail, wether $a_1 or $a_2. How do I do that?.
the codeigniter wiki sais this
$data = array(
'name' => $a_1['name'],
'mail' => $a_2['mail'],
);
$this->load->view('confirm_data_v', $data);
https://www.codeigniter.com/user_guide/general/views.html
You're passing the arrays in an incorrect way. You can only pass one data array as a second parameter while loading the view.
You could instead put each array in the data array in your controller:
$data['a_1'] = $a_1;
$data['a_2'] = $a_2;
$this->load->view('confirm_data_v', $data);
Then in your view you can access $a_1 and $a_2 as you like
Name: <?php echo $a_1['name']; ?>
Email: <?php echo $a_2['mail']; ?>

Categories